Get the union of two sets in Java



The union of two sets combines all the unique elements from both sets into one. In Java we can achieve this using the HashSet class, which ensures no duplicate elements. This article will demonstrate two approaches to finding the union of two sets. 

Different Approaches 

Following are the two different approaches to getting the union of two sets in Java ?

Using the addAll() Method

The simplest way to find the union of two sets is by using the addAll() method of the HashSet class. This method adds all the elements of one set into another while maintaining uniqueness.

addAll() method: The addAll() method: ensures that unique elements are added, as duplicates are not allowed in a HashSet.

set1.addAll(set2); // Combine set2 into set1

Example

Below is an example of getting the union of two sets using the addAll() method ?

import java.util.*;
public class addAll {
	public static void main(String args[]) {
		HashSet set1 = new HashSet<>();
		HashSet set2 = new HashSet<>();

		set1.add("Mat");
		set1.add("Sat");
		set1.add("Cat");
		System.out.println("Set1 = " + set1);

		set2.add("Mat");
		set2.add("Cat");
		set2.add("Fat");
		set2.add("Hat");
		System.out.println("Set2 = " + set2);

		set1.addAll(set2); // Combine set2 into set1
		System.out.println("Union = " + set1);
	}
}

Output

Set1 = [Mat, Sat, Cat]
Set2 = [Mat, Cat, Fat, Hat]
Union = [Mat, Sat, Cat, Fat, Hat]

Explanation

  • Two HashSet objects (set1 and set2) are created.
  • The add() method adds elements to each set.
  • The addAll() method merges the elements of set2 into set1, ensuring no duplicates.

Using Streams

Another way to find the union is by using Java 8 Streams. This method is simpler and more concise, using the Stream API and Collectors for merging collections.

Use Stream.concat and collect to a Set ?

Set union = Stream.concat(set1.stream(), set2.stream())
.collect(Collectors.toSet());

Example

Below is an example of getting the union of two sets using the streams ?

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class DemoStream {
   public static void main(String[] args) {
      // Define sets with explicit generic type <String>
      Set<String> set1 = new HashSet<>(Arrays.asList("Mat", "Sat", "Cat"));
      Set<String> set2 = new HashSet<>(Arrays.asList("Mat", "Cat", "Fat", "Hat"));
      
      System.out.println("Set1 = " + set1);
      System.out.println("Set2 = " + set2);
      
      // Use Stream.concat and collect to a Set<String>
      Set<String> union = Stream.concat(set1.stream(), set2.stream())
                                .collect(Collectors.toSet());
      System.out.println("Union = " + union);
   }
}

Output

Set1 = [Mat, Sat, Cat]
Set2 = [Mat, Cat, Fat, Hat]
Union = [Mat, Sat, Cat, Fat, Hat] 

Explanation

  • The Stream.concat() method combines the streams of both sets.
  • The combined stream is collected into a new set using Collectors.toSet(), which ensures unique elements.

Comparison Table

Aspect addAll() Method Streams Approach
Readability Simple and straightforward More verbose but functional style
Performance Generally faster for smaller sets May have slight overhead due to stream operations
Mutability Modifies original set (set1) Creates a new set (immutable approach)
Updated on: 2025-01-28T14:55:40+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements