• Java Data Structures Tutorial

Java Data Structures - Subtract two Sets



Suppose we have formed/created a set object by adding the contents two sets (or more) and when you need to remove the contents of a particular set altogether from this you can do it using the removeAll() method.

This method belongs to set interface and it is inherited from the collection interface. It accepts a collection objects and removes the contents of it from the current Set (object) altogether at once.

Example

import java.util.HashSet;
import java.util.Set;

public class SubtractingTwoSets {
   public static void main(String args[]) {      
      Set set1 = new HashSet();      
      set1.add(100);
      set1.add(501);
      set1.add(302);
      set1.add(420);
      System.out.println("Contents of set1 are: ");
      System.out.println(set1); 

      Set set2 = new HashSet();      
      set2.add(200);
      set2.add(630);
      set2.add(987);
      set2.add(665);
      System.out.println("Contents of set2 are: ");
      System.out.println(set2); 
      
      set1.addAll(set2);
      System.out.println("Contents of set1 after addition: ");
      System.out.println(set1);
      
      set1.removeAll(set2);
      System.out.println("Contents of set1 after removal");
      System.out.println(set1);
   }
}

Output

Contents of set1 are: 
[100, 420, 501, 302]
Contents of set2 are: 
[630, 200, 665, 987]
Contents of set1 after addition: 
[100, 420, 501, 630, 200, 665, 987, 302]
Contents of set1 after removal
[100, 420, 501, 302]
Advertisements