HashSet remove() Method in Java
Last Updated :
05 Oct, 2021
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
import java.util.*;
public class GFG {
public static void main(String args[])
{
HashSet<String> set = new HashSet<String>();
set.add("Welcome");
set.add("To");
set.add("Geeks");
set.add("For");
set.add("Geeks");
System.out.println("HashSet: " + set);
set.remove("Geeks");
set.remove("For");
set.remove("Welcome");
System.out.println(
"HashSet after removing elements: " + set);
}
}
|
Output
HashSet: [Geeks, For, Welcome, To]
HashSet after removing elements: [To]
Example 2:
Java
import java.util.*;
public class GFG {
public static void main(String args[])
{
HashSet<Integer> set = new HashSet<Integer>();
set.add(5);
set.add(3);
set.add(1);
set.add(4);
set.add(3);
System.out.println("HashSet: " + set);
set.remove(3);
set.remove(1);
System.out.println(
"HashSet after removing elements: " + set);
}
}
|
Output
HashSet: [1, 3, 4, 5]
HashSet after removing elements: [4, 5]
Please Login to comment...