Syntax error Get the intersection of two sets in Java

Get the intersection of two sets in Java



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]
Updated on: 2020-06-29T08:07:56+05:30

15K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements