How to Remove Set From HashSet

We can remove set from Hashset with the help removeAll() method. Hashset removeAll() method in java removes from this set all of its elements that are contained in the specified collection.

Syntax :

public boolean removeAll(Collection<?> c){

   }
  • Parameters – c collection containing elements to be removed from this set
  • Returns Value-  It return true if this set changed as a result of the call.
  • Exception –  It throws following exceptions :
    UnsupportedOperationException – if the removeAll operation is not supported by this set
    ClassCastException – if the class of an element of this set is incompatible with the specified collection (optional)
    NullPointerException – if this set contains a null element and the specified collection does not permit null elements (optional), or if the specified collection is null
package com.javapro.hashset;

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

public class RemoveAll {

public static void main(String[] args) {

Set<String> hs = new HashSet<String>();
hs.add("java");
hs.add("php");
hs.add("html");
hs.add("javascript");
hs.add("mysql");

// print hashset
System.out.println("Before Remove Element hs = " + hs);

HashSet<String> hs2 = new HashSet<String>();
hs2.add("java");
hs2.add("html");
hs2.add("two");

System.out.println("hs2 is = " + hs2);

/*
* Removes from hs set all of its elements that are contained in the hs2
* collection
*/

hs.removeAll(hs2);

System.out.println("After Remove All hs = " + hs);

}

}

Output:

Before Remove Element hs = [javascript, php, html, java, mysql]

hs2 is = [two, html, java]

After Remove All hs = [javascript, php, mysql]

A Guide to HashSet

 

Leave a Reply

Your email address will not be published. Required fields are marked *

85 − 81 =