Merge two sets in Java

JavaObject Oriented ProgrammingProgramming

To merge two sets in Java, the code is as follows −

Example

 Live Demo

import java.util.stream.*;
import java.util.*;
import java.io.*;
public class Demo{
   public static <T> Set<T> set_merge(Set<T> set_1, Set<T> set_2){
      Set<T> my_set = set_1.stream().collect(Collectors.toSet());
      my_set.addAll(set_2);
      return my_set;
   }
   public static void main(String[] args){
      Set<Integer> my_set_1 = new HashSet<Integer>();
      my_set_1.addAll(Arrays.asList(new Integer[] { 34, 67, 89, 102 }));
      Set<Integer> my_set_2 = new HashSet<Integer>();
      my_set_2.addAll(Arrays.asList(new Integer[] { 77, 11, 0 , -33}));
      System.out.println("The first set contains " + my_set_1);
      System.out.println("The second set contains " + my_set_2);
      System.out.println("The two sets are merged " + set_merge(my_set_1, my_set_2));
   }
}

Output

The first set contains [34, 67, 102, 89]
The second set contains [0, -33, 11, 77]
The two sets are merged [0, -33, 34, 67, 102, 89, 11, 77]

A class named Demo contains a function named ‘set_merge’ that uses the ‘addAll’ function to merge the two sets that are passed as parameters to the function. In the main function, two sets are defined and elements are added into it using the ‘addAll’ function. Relevant messages are printed on the console.

raja
Published on 07-Jul-2020 11:50:49
Advertisements