What is the simplest way to make a union or an intersection of Set
s in Java? I've seen some strange solutions to this simple problem (e.g. manually iterating the two sets).
Let's use the Guava Sets class to perform intersection and union on our example sets. In order to do this we can simply use the static methods union and intersection of the Sets class: Set<Integer> intersectSet = Sets. intersection(setA, setB); assertEquals(setOf(2,4), intersectSet); Set<Integer> unionSet = Sets.
Java For Testers To get the union of two sets, use the addAll() method.
Java Array. Learn to find the union between two arrays in Java using HashSet class. In set theory, the union (denoted by U) of a collection of sets is the set of all elements in the collection. For example, the union of two sets A and B is the set of all the elements which are either in A, or in B, or in both A and B.
The union of two sets contains elements from both sets with no duplicates. The intersection of two sets contains elements that are common to both sets. The difference of two sets, s1 and s2, is a set that contains all elements of s1 that are not in s2.
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
While guava for sure is neater and pretty much standard, here's a non destructive way to do union and intersect using only standard Java
Set s1 = Set.of(1,2,3); Set s2 = Set.of(3,4,5); Set union = Stream.concat(s1.stream(),s2.stream()).collect(Collectors.toSet()); Set intersect = s1.stream().filter(s2::contains).collect(Collectors.toSet());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With