Last Updated : 11 Jul, 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);
}
}
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);
}
}
Was 2 removed? true Was 10 removed? false
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4