Union or intersection of Java Sets

Mahozad picture Mahozad · Jun 30, 2018 · Viewed 41.4k times · Source

What is the simplest way to make a union or an intersection of Sets in Java? I've seen some strange solutions to this simple problem (e.g. manually iterating the two sets).

Union/Intersection of Java sets

Answer

Mahozad picture Mahozad · Jun 30, 2018

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