1 /* 2 * Copyright (C) 2017 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.settings.intelligence.suggestions.model; 18 19 import android.service.settings.suggestions.Suggestion; 20 import android.util.ArraySet; 21 22 import java.util.ArrayList; 23 import java.util.HashMap; 24 import java.util.List; 25 import java.util.Map; 26 import java.util.Set; 27 28 public class SuggestionListBuilder { 29 30 private Map<SuggestionCategory, List<Suggestion>> mSuggestions; 31 private boolean isBuilt; 32 33 public SuggestionListBuilder() { 34 mSuggestions = new HashMap<>(); 35 } 36 37 public void addSuggestions(SuggestionCategory category, List<Suggestion> suggestions) { 38 if (isBuilt) { 39 throw new IllegalStateException("Already built suggestion list, cannot add new ones"); 40 } 41 mSuggestions.put(category, suggestions); 42 } 43 44 public List<Suggestion> build() { 45 isBuilt = true; 46 return dedupeSuggestions(); 47 } 48 49 /** 50 * Filter suggestions list so they are all unique. 51 */ 52 private List<Suggestion> dedupeSuggestions() { 53 final Set<String> ids = new ArraySet<>(); 54 final List<Suggestion> suggestions = new ArrayList<>(); 55 for (List<Suggestion> suggestionsInCategory : mSuggestions.values()) { 56 suggestions.addAll(suggestionsInCategory); 57 } 58 for (int i = suggestions.size() - 1; i >= 0; i--) { 59 final Suggestion suggestion = suggestions.get(i); 60 final String id = suggestion.getId(); 61 if (ids.contains(id)) { 62 suggestions.remove(i); 63 } else { 64 ids.add(id); 65 } 66 } 67 return suggestions; 68 } 69 }