Syntax error Get the asymmetric difference of two sets in Java

Get the asymmetric difference of two sets in Java



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]
Updated on: 2020-06-25T10:26:24+05:30

696 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements