Example 1: Calculate the difference between two sets
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
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.