HashSet remove() method is used to remove a particular element from a HashSet. Note that it is only after JDK version 1.2 and ahead, and will throw compilation errors before in version JDK 1 and JDK1.1.
Note: This method returns true if the specified element is present in the HashSet otherwise it returns boolean false.
Syntax:
HashSet.remove(Object O)
Parameters: The parameter O is of the type of HashSet and specifies the element to be removed from the HashSet.
Return Value: Boolean true and false
Example 1:
Java
// Java code to illustrate // HashSet.remove() method // over String Elements // Importing required classes import java.util.*; // Main class // HashSet demo public class GFG { // Main driver method public static void main(String args[]) { // Creating an empty HashSet // Declaring object of string type HashSet<String> set = new HashSet<String>(); // Adding custom input elements into the Set // using add() method set.add( "Welcome" ); set.add( "To" ); set.add( "Geeks" ); set.add( "For" ); set.add( "Geeks" ); // Displaying the HashSet(object elements) System.out.println( "HashSet: " + set); // Removing elements // using remove() method set.remove( "Geeks" ); set.remove( "For" ); set.remove( "Welcome" ); // Now displaying the HashSet after removal // of elements from it System.out.println( "HashSet after removing elements: " + set); } } |
HashSet: [Geeks, For, Welcome, To] HashSet after removing elements: [To]
Example 2:
Java
// Java code to illustrate remove() // method of Hashset class // over Integer Elements // Importing required classes import java.util.*; // Main class public class GFG { // Main driver method public static void main(String args[]) { // Creating an empty HashSet // Declaring object of integer type HashSet<Integer> set = new HashSet<Integer>(); // Adding custom input elements into the Set // using add() method set.add( 5 ); set.add( 3 ); set.add( 1 ); set.add( 4 ); set.add( 3 ); // Displaying the HashSet(object elements) System.out.println( "HashSet: " + set); // Removing elements // using remove() method set.remove( 3 ); set.remove( 1 ); // Now displaying the HashSet after removal // of elements from it System.out.println( "HashSet after removing elements: " + set); } } |
HashSet: [1, 3, 4, 5] HashSet after removing elements: [4, 5]