Example 1: Calculate the intersection of two sets
import java.util.HashSet;
import java.util.Set;
class Main {
public static void main(String[] args) {
// create first set
Set<Integer> primeNumbers = new HashSet<>();
primeNumbers.add(2);
primeNumbers.add(3);
System.out.println("Prime Numbers: " + primeNumbers);
// create second set
Set<Integer> evenNumbers = new HashSet<>();
evenNumbers.add(2);
evenNumbers.add(4);
System.out.println("Even Numbers: " + evenNumbers);
// Intersection of two sets
evenNumbers.retainAll(primeNumbers);
System.out.println("Intersection: " + evenNumbers);
}
}
Output
Prime Numbers: [2, 3] Even Numbers: [2, 4] Intersection: [2]
In the above example, we have created two sets named primeNumbers and evenNumbers. We have implemented the set using the HashSet
class. Notice the line,
evenNumbers.retainAll(primeNumbers);
Here, we have used the retainAll() method to get the intersection of two sets.
Example 2: Get union of two sets using Guava Library
import java.util.HashSet;
import java.util.Set;
import com.google.common.collect.Sets;
class Main {
public static void main(String[] args) {
// create the first set
Set<String> backend = new HashSet<>();
backend.add("Java");
backend.add("JavaScript");
System.out.println("Backend Languages: " + backend);
// create second set
Set<String> frontend = new HashSet<>();
frontend.add("JavaScript");
frontend.add("CSS");
System.out.println("Frontend Languages: " + frontend);
Set<String> intersect = Sets.intersection(backend, frontend);
System.out.println("Common Languages: " + intersect);
}
}
Output
Backend Languages: [Java, JavaScript] Frontend Languages: [JavaScript, CSS] Common Languages: [JavaScript]
In the above example, we have used the Guava library to get the intersection of two sets. In order to run this program, you need to implement Guava Library by adding it to your dependency.
Here, we have used the intersection()
method of the Sets class present in the Guava library.