Write a Java Program to Calculate union of two sets

In Java, sets are collections of unique elements.

The union of two sets is a set containing all the distinct elements from both sets.

In this tutorial, we will learn how to calculate the union of two sets using Java programming language.


To get started, we need to create two sets with some elements in them.

We can use the HashSet class provided by Java Collections framework to create sets.

HashSet is an implementation of the Set interface and it provides constant-time performance for basic operations such as add, remove, contains, and size.

Let’s create two sets of integers:

Set<Integer> set1 = new HashSet<>(Arrays.asList(1, 2, 3, 4));
Set<Integer> set2 = new HashSet<>(Arrays.asList(3, 4, 5, 6));

Here, we have created two sets, set1 and set2, with some integers in them.

To calculate the union of these two sets, we can simply add all the elements from set2 to set1 using the addAll() method.

This method adds all the elements from the specified collection to the set. Since sets only contain unique elements, duplicates will automatically be eliminated.

set1.addAll(set2);

After executing this line of code, the set1 will contain all the elements from both sets without any duplicates.

We can print out the elements of the union set using a for-each loop:

for (int element : set1) {
    System.out.print(element + " ");
}

This will print out: 1 2 3 4 5 6

Here’s the complete code to calculate the union of two sets:

import java.util.*;

public class UnionOfSets {
    public static void main(String[] args) {
        Set<Integer> set1 = new HashSet<>(Arrays.asList(1, 2, 3, 4));
        Set<Integer> set2 = new HashSet<>(Arrays.asList(3, 4, 5, 6));
        
        set1.addAll(set2);
        
        System.out.println("Union of set1 and set2: ");
        for (int element : set1) {
            System.out.print(element + " ");
        }
    }
}

Output:

Union of set1 and set2: 
1 2 3 4 5 6

In conclusion, we can easily calculate the union of two sets using the addAll() method provided by the HashSet class.

This method adds all the elements from the specified collection to the set and eliminates any duplicates automatically.