Skip to content

Instantly share code, notes, and snippets.

@bigntallmike
Last active March 4, 2020 18:26
Show Gist options
  • Save bigntallmike/7a24baf292b23a60a3f6691bf7120aed to your computer and use it in GitHub Desktop.
Save bigntallmike/7a24baf292b23a60a3f6691bf7120aed to your computer and use it in GitHub Desktop.
Find the intersection of N lists contained in SearchResults
if (SearchResults.size() == 1) {
DATA = SearchResults.get(0);
} else {
/* Find the smallest list */
int baseitem = 0;
for (int i = 1; i < SearchResults.size(); i++) {
if (SearchResults.get(i).size() < SearchResults.get(baseitem).size()) {
baseitem = i;
}
}
/* Initialize DATA to be the maximum size it could need to be */
DATA = new ArrayList<type>(SearchResults.get(baseitem).size());
/* Now take the intersection of those lists, looping through one list and comparing */
for (DataType Record : SearchResults.get(baseitem)) {
Boolean matched = true;
for (int i = 0; i < SearchResults.size(); i++) {
if (i == baseitem) {
break;
}
if (!SearchResults.get(i).contains(Record)) {
matched = false;
break;
}
}
if (matched) {
DATA.add(Record);
}
}
DATA.trimToSize();
}
@bigntallmike
Copy link
Author

Would be faster if we saved position in each secondary list as items in the primary were found, as in sorted results the new results cannot be found before the old ones.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment