Merge two sets in Java

In this tutorial, we will learn how to merge two sets in Java. We will merge and sort the sets in ascending order.

Now we are going to look into examples to help give us an idea and better understanding of this question.

We are going to take two different sets as inputs and as output we will get one merged set.

Example 1:

Input:

Set A: [1,3,5,7,9]

Set B: [0,2,4,6,8]

Output:

Merged Set: [0,1,2,3,4,5,6,7,8,9]

Example 2:

Set A: [3,4,7,8,9]

Set B: [0,1,2,5,6]

Output:

Merged Set: [0,1,2,3,4,5,6,7,8,9]

So, here we take two different input sets, and then we get a new merged set which is also a sorted set which you can see.

Now we will look into the code.

CODE:

import java.util.*;
public class main { 
    public static <T> Set<T> mergeSet(Set<T> a, Set<T> b) 
    { 
        return new HashSet<T>() {{ 
                      addAll(a); 
                       addAll(b); 
        } }; 
    } 
  
    public static void main(String[] args) 
    {  
        Set<Integer> a = new HashSet<Integer>(); 
        a.addAll(Arrays.asList(new Integer[] { 8,4, 3, 7, 9 })); 
        Set<Integer> b = new HashSet<Integer>(); 
        b.addAll(Arrays.asList(new Integer[] { 0, 5, 1, 2, 6 })); 
        System.out.println(a); 
        System.out.println(b);  
        System.out.println(mergeSet(a, b)); 
    } 
}
Input:

[3,4,7,8,9]

[1,2,3,4,5,6]

Output:

[1,2,3,4,5,6,7,8,9]

Also read: How to convert a Set to Stream in Java

Leave a Reply

Your email address will not be published. Required fields are marked *