How to calculate the intersection of two sets?

Use the retainAll() method of Set: Set<String> s1; Set<String> s2; s1.retainAll(s2); // s1 now contains only elements in both sets If you want to preserve the sets, create a new set to hold the intersection: Set<String> intersection = new HashSet<String>(s1); // use the copy constructor intersection.retainAll(s2); The javadoc of retainAll() says it’s exactly what you want: Retains only the elements in this set that … Read more

Union or intersection of Java Sets

The simplest one-line solution is this: set1.addAll(set2); // Union set1.retainAll(set2); // Intersection The above solution is destructive, meaning that contents of the original set1 my change.If you don’t want to touch your existing sets, create a new set: Set<E> result = new HashSet<>(set1); // └─ your specific type result.addAll(set2); // Union result.retainAll(set2); // Intersection