Java Program to Calculate the difference between two sets

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<>();
    numbers.add(1);
    numbers.add(2);
    numbers.add(3);
    numbers.add(4);
    System.out.println("Numbers: " + numbers);

    // create second set
    Set<Integer> primeNumbers = new HashSet<>();
    primeNumbers.add(2);
    primeNumbers.add(3);
    System.out.println("Prime Numbers: " + primeNumbers);

    // Difference between HashSet1 and HashSet2
    numbers.removeAll(primeNumbers);
    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;
import com.google.common.collect.Sets;

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

    // create the first set
    Set<String> languages1 = new HashSet<>();
    languages1.add("Java");
    languages1.add("JavaScript");
    languages1.add("English");
    languages1.add("Spanish");
    System.out.println("Languages: " + languages1);

    // create second set
    Set<String> languages2 = new HashSet<>();
    languages2.add("English");
    languages2.add("Spanish");
    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.

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges