Java Program to Calculate the intersection of two sets

To understand this example, you should have the knowledge of the following Java programming topics:


Example 1: Calculate the intersection of two sets

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

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.