Improve duplicate removal run time by using a hash set

This commit is contained in:
orelogo 2017-02-25 17:22:57 -08:00
parent 352b6747cf
commit a1201cc95f
1 changed files with 6 additions and 18 deletions

View File

@ -4,7 +4,9 @@ import android.content.Context;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask; import java.util.concurrent.FutureTask;
@ -51,15 +53,17 @@ public class FeedSearcher {
task.run(); task.run();
} }
try { try {
Set<Long> set = new HashSet<>();
for (int i = 0; i < tasks.size(); i++) { for (int i = 0; i < tasks.size(); i++) {
FutureTask<List<FeedItem>> task = tasks.get(i); FutureTask<List<FeedItem>> task = tasks.get(i);
List<FeedItem> items = task.get(); List<FeedItem> items = task.get();
for (FeedItem item : items) { for (FeedItem item : items) {
if (result.isEmpty() || !isDuplicate(result, item)) { if (!set.contains(item.getId())) { // to prevent duplicate results
result.add(new SearchResult(item, values[i], subtitles[i])); result.add(new SearchResult(item, values[i], subtitles[i]));
set.add(item.getId());
} }
} }
} }
} catch (InterruptedException | ExecutionException e) { } catch (InterruptedException | ExecutionException e) {
e.printStackTrace(); e.printStackTrace();
@ -67,20 +71,4 @@ public class FeedSearcher {
Collections.sort(result, new SearchResultValueComparator()); Collections.sort(result, new SearchResultValueComparator());
return result; return result;
} }
/**
* Determines if the feed item is already in the search result list.
*
* @param result list of search results
* @param item feed item to validate
* @return true if the feed item is already in the results
*/
private static boolean isDuplicate(List<SearchResult> result, FeedItem item) {
for (SearchResult resultItem : result) {
if (resultItem.getComponent().getId() == item.getId()) {
return true;
}
}
return false;
}
} }