Get the asymmetric difference of two sets in Java

Java 8Object Oriented ProgrammingProgramming

Use removeAll() method to get the asymmetric difference of two sets.

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");

To get the asymmetric difference −

set1.removeAll(set2);

The following is an example that displays how to get the asymmetric difference between 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");
      System.out.println("Set2 = "+ set2);
      set1.removeAll(set2);
      System.out.println("Asymmetric difference = "+ set1);
   }
}

Output

Set1 = [Mat, Sat, Cat]
Set2 = [Mat]
Asymmetric difference = [Sat, Cat]
raja
Published on 10-Jan-2019 13:45:46
Advertisements