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:

var result = new HashSet<>(set1);          // In Java 10 and above
Set<Integer> result = new HashSet<>(set1); // In Java < 10
result.addAll(set2); // Union
result.retainAll(set2); // Intersection

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)