Java Utility Library

Java HashSet - remove() Method



The java.util.HashSet.remove() method is used to remove the specified element from the set, if it is present. Every removal of element results into reducing the set size by one unless the set is empty.

Syntax

public boolean remove(Object obj)

Parameters

obj Specify the element which need to be removed from this set, if present.

Return Value

Returns true if this set contained the specified element.

Exception

NA.

Example:

In the example below, the java.util.HashSet.remove() method is used to remove the specified element from the given set.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating hash set
    HashSet<Integer> MySet = new HashSet<Integer>();

    //populating hash set
    MySet.add(10);
    MySet.add(20);
    MySet.add(30);
    MySet.add(40);

    //printing hash set
    System.out.println("MySet contains: " + MySet);

    //remove 30 from the set
    MySet.remove(30);

    //printing hash set
    System.out.println("MySet contains: " + MySet);
  }
}

The output of the above code will be:

MySet contains: [20, 40, 10, 30]
MySet contains: [20, 40, 10]

❮ Java.util - HashSet