How to remove the specific element from the hashset

How to remove the specific element from the hashset

Previous Home Next

 

This example will shows how the particular element is removed from the Hashset.

Using remove method of Hashset class we will remove the specific element from the Hashset table.
 Boolean Remove method of Hashset class returns true if the element is removed from the Hashset otherwise it returns false.

 boolean blnRemoved = hSet.remove(new Integer("21"));
method check the value in Hashset and will return the Boolean value for its removal.

 


import java.util.HashSet;
public class FieldHash {


public static void main(String[] args) {
HashSet hSet = new HashSet();
hSet.add(new Integer("5"));
hSet.add(new Integer("3"));
hSet.add(new Integer("21"));
hSet.add(new Integer("54"));
System.out.println("HashSet elements before removal : " + hSet);
boolean blnRemoved = hSet.remove(new Integer("21"));
System.out.println("is 21 removed from HashSet ? " + blnRemoved);
System.out.println("HashSet elements after removal : " + hSet);


}

}

HashSet elements  before removal : [3, 21, 54, 5]
Is 21 removed from HashSet ? true
HashSet elements after removal : [3, 54, 5]

Previous Home Next