Remove HashSet elements
We can use remove() method of HashSet to remove elements from HashSet collection
boolean remove(Object obj)
Example
- import java.util.*;
- public class HashSetRemoveExample {
- public static void main(String args[]) {
- HashSet<String> hs = new HashSet<String>();
- hs.add("java");
- hs.add("c");
- hs.add("c++");
- System.out.println("HashSet before removing elements");
- System.out.println(hs);
- hs.remove("java");
- System.out.println("HashSet after removing elements");
- System.out.println(hs);
- }
- }
import java.util.*; public class HashSetRemoveExample { public static void main(String args[]) { HashSet<String> hs = new HashSet<String>(); hs.add("java"); hs.add("c"); hs.add("c++"); System.out.println("HashSet before removing elements"); System.out.println(hs); hs.remove("java"); System.out.println("HashSet after removing elements"); System.out.println(hs); } }
Removing all elements at once
We can use clear() method of HashSet to remove all elements in one go
Example
- import java.util.*;
- public class HashSetRemoveAllExample {
- public static void main(String args[]) {
- HashSet<String> hs = new HashSet<String>();
- hs.add("java");
- hs.add("c");
- hs.add("c++");
- System.out.println("HashSet before removing all elements");
- System.out.println(hs);
- hs.clear();
- System.out.println("HashSet after removing all elements");
- System.out.println(hs);
- }
- }
import java.util.*; public class HashSetRemoveAllExample { public static void main(String args[]) { HashSet<String> hs = new HashSet<String>(); hs.add("java"); hs.add("c"); hs.add("c++"); System.out.println("HashSet before removing all elements"); System.out.println(hs); hs.clear(); System.out.println("HashSet after removing all elements"); System.out.println(hs); } }