Get the intersection of two sets in Java

Java 8Object Oriented ProgrammingProgramming

To get the intersection of two sets, use the retainAll() method. Here are out two set −

First set −

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

Second set −

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

Get the intersection −

set1.retainAll(set2);

The following is an example to get the intersection of two sets −

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.retainAll(set2);
      System.out.println("Intersection = "+ set1);
   }
}

Output

Set1 = [Mat, Sat, Cat]
Set2 = [Mat, Cat, Fat, Hat]
Intersection = [Mat, Cat]
raja
Published on 10-Jan-2019 13:50:09
Advertisements