So if I'm understanding correctly you already have a set for each Integer listing its adjacency?
The easiest efficient way I can see to do this is to make use of another Set. Sets are very fast for checking if they already contain values.
Set<Integer> adjacent = new HashSet<>();
for (Integer i: toCheck) {
int oldCount = adjacent.size();
Set<Integer> check = adjacencyLists.get(i);
adjacent.addAll(check);
if (adjacent.size() != oldCount+check.size()) {
// Duplicate found
return true;
}
}
return false;
If you need to know the identify of the common then loop through doing individual add calls instead of doing the addAll and check each add for success. This may actually be more efficient as no need to do the size checks:
Set<Integer> adjacent = new HashSet<>();
for (Integer i: toCheck) {
Set<Integer> check = adjacencyLists.get(i);
for (Integer c: check)
if (!adjacent.add(c)) {
// Duplicate found
return c;
}
}
return null;
Just saw the request for the full list of common members:
Set<Integer> adjacent = new HashSet<>();
Set<Integer> results = new HashSet<>();
for (Integer i: toCheck) {
Set<Integer> check = adjacencyLists.get(i);
for (Integer c: check)
if (!adjacent.add(c)) {
// Duplicate found
results.add(c);
}
}
return results;