Get the union of two sets in Java


To get the union of two sets, use the addAll() method.

The first set −

HashSet <String> set1 = new HashSet <String>();
set1.add("Mat");
set1.add("Sat");
set1.add("Cat");

The second set −

HashSet <String> set2 = new HashSet <String>();
set2.add("Mat");
set2.add("Cat");
set2.add("Fat");
set2.add("Hat");

Get the union −

set1.addAll(set2);

The following is an example −

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      HashSet <String> set1 = new HashSet <String>();
      HashSet <String> set2 = new HashSet <String>();
      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);
      System.out.println("Union = "+ set1);
   }
}

Output

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

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 25-Jun-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements