Java Program to Calculate union of two sets

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


Example 1: Calculate the union of two sets using addAll()

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

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

    // create the first set
    Set<Integer> evenNumbers = new HashSet<>();
    evenNumbers.add(2);
    evenNumbers.add(4);
    System.out.println("Set1: " + evenNumbers);

    // create second set
    Set<Integer> numbers = new HashSet<>();
    numbers.add(1);
    numbers.add(3);
    System.out.println("Set2: " + numbers);

    // Union of two sets
    numbers.addAll(evenNumbers);
    System.out.println("Union is: " + numbers);
  }
}

Output

Set1: [2, 4]
Set2: [1, 3]
Union is: [1, 2, 3, 4]

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

numbers.addAll(evenNumbers);

Here, we have used the addAll() method to get the union of two sets.


Example 2: Get union of 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("Python");
    System.out.println("Programming Languages: " + languages1);

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

    Set<String> unionSet = Sets.union(languages1, languages2);
    System.out.println("Union is: " + unionSet);
  }
}

Output

Programming Languages: [Java, Python]
Human Languages: [English, Spanish]
Languages: [Java, Python, English, Spanish]

In the above example, we have used the Guava library to get the union of 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 union() 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