 # Java Program to Calculate the difference between two sets

In this example, we will learn to calculate the difference between two sets in Java.

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

## Example 1: Calculate the difference between two sets

``````import java.util.HashSet;
import java.util.Set;

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

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

// create second set

// Difference between HashSet1 and HashSet2
System.out.println("Numbers without prime numbers: " + numbers);
}
}``````

Output

```Numbers: [1, 2, 3, 4]
Prime Numbers: [2, 3]
Numbers without prime numbers: [1, 4]```

In the above example, we have created two sets named numbers and primeNumbers. We have implemented the set using the `HashSet` class. Notice the line,

``numbers.retainAll(primeNumbers);``

Here, we have used the `removeAll()` method to calculate the difference between two sets.

## Example 2: Get difference between 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> languages1 = new HashSet<>();
System.out.println("Languages: " + languages1);

// create second set
Set<String> languages2 = new HashSet<>();
System.out.println("Human Languages: " + languages2);

Set<String> intersect = Sets.difference(languages1, languages2);
System.out.println("Programming Languages: " + intersect);
}
}``````

Output

```Languages: [Java, JavaScript, English, Spanish]
Human Languages: [English, Spanish]
Programming Languages: [Java, JavaScript]```

In the above example, we have used the Guava library to get the difference between two sets. In order to run this program, you need to implement Guava Library by adding it in your dependency.

Here, we have used the `difference()` method of the Sets class present in the Guava library.