How can you find the intersection of multiple (more than two) sets in Java?
retainAll
by itself wont work since I need the ability to get the intersection between more than just two sets
How can you find the intersection of multiple (more than two) sets in Java?
retainAll
by itself wont work since I need the ability to get the intersection between more than just two sets
public static <T> Collection<T> getIntersection(Collection<T>... sets) {
Collection<T> firstSet;
if (sets == null || sets.length == 0 || (firstSet = sets[0]) == null)
return Collections.<T>emptySet();
Collection<T> intersection = new HashSet(firstSet);
for (Collection c : sets) {
if (c == null)
return Collections.<T>emptySet();
intersection.retainAll(c);
}
return intersection;
}
You can use the Set's retainAll(other)
method which retains only items that are in both sets. It alters the original set, so you may want to take a copy of the set first (use the appropriate constructor).