 # Java Program to Calculate the intersection of two sets

In this example, we will learn to calculate the intersection of two sets in Java.

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

## 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

// create second set
Set<Integer> evenNumbers = new HashSet<>();
System.out.println("Even Numbers: " + evenNumbers);

// Intersection of two sets
System.out.println("Intersection: " + evenNumbers);
}
}``````

Output

```Prime Numbers: [2, 3]
Even Numbers: [2, 4]
Intersection:  ```

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;

class Main {
public static void main(String[] args) {

// create the first set
Set<String> backend = new HashSet<>();
System.out.println("Backend Languages: " + backend);

// create second set
Set<String> frontend = new HashSet<>();
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.