Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Union or intersection of Java Sets

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

like image 702
Mahozad Avatar asked Jun 30 '18 08:06

Mahozad


People also ask

How do you find the union and intersection of two sets in Java?

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.

How do you set a union in Java?

Java For Testers To get the union of two sets, use the addAll() method.

What is union in Java?

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.

What are the set methods for set difference set union and set intersection?

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.


2 Answers

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 
like image 165
Mahozad Avatar answered Sep 19 '22 22:09

Mahozad


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()); 
like image 21
David Lilljegren Avatar answered Sep 20 '22 22:09

David Lilljegren