HashSet remove() Method in Java (original) (raw)

Last Updated : 10 Mar, 2025

The HashSet remove() method in Java is used to remove a specific element from the set if it is present.

**Note: HashSet and the remove() were introduced in JDK 1.2 as part of the Collections Framework and are not available in earlier versions of Java (JDK 1.0 and JDK 1.1).

**Example 1: Here, the remove() method is used to remove a specified element from the set.

Java `

// Java Program to demonstrates the working of remove() import java.util.*;

public class Geeks {

public static void main(String args[])
{
    // Create a HashSet
    HashSet<Integer> s = new HashSet<>();
    //  add elements into a HashSet
    s.add(1);
    s.add(2);
    s.add(3);
    s.add(4);
    s.add(5);

    System.out.println("Original HashSet: " + s);

    s.remove(2);

    // Now displaying the HashSet after removal
    System.out.println(
        "HashSet after removing elements: " + s);
}

}

`

Output

Original HashSet: [1, 2, 3, 4, 5] HashSet after removing elements: [1, 3, 4, 5]

Syntax of HashSet remove() Method

public boolean remove(Object o)

**Example 2: This example demonstrates that the remove() method in a HashSet returns a boolean value indicating whether the specified element was successfully removed.

Java `

// To demonstrates that remove() method return boolean value import java.util.*; public class Geeks {

public static void main(String args[])
{
    // Create a HashSet
    HashSet<Integer> s = new HashSet<>();
    
    // Add elements into a HashSet
    s.add(1);
    s.add(2);
    s.add(3);
    s.add(4);
    s.add(5);
    
    boolean b = s.remove(2);
    System.out.println("Was 2 removed? " +b);

    boolean n = s.remove(10);
    System.out.println("Was 10 removed? " +n);

}

}

`

Output

Was 2 removed? true Was 10 removed? false