In this post we will see various ways to remove elements from HashSet in java.
We can either use remove(Object o) OR an Iterator<E>
1. Example : Remove Elements from HashSet using remove()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
package com.kscodes.sampleproject; import java.util.HashSet; import java.util.Set; public class HashSetRemoveExample { public static void main(String[] args) { Set<String> hashSet = new HashSet<>(); hashSet.add("Java"); hashSet.add("Spring"); hashSet.add("Hibernate"); hashSet.add("JavaScript"); System.out.println("HashSet before removing any element :: " + hashSet.toString()); // Now remove "Spring" hashSet.remove("Spring"); System.out.println("HashSet after removing element :: " + hashSet.toString()); } } |
Output
1 2 |
HashSet before removing any element :: [Hibernate, Spring, JavaScript, Java] HashSet after removing element :: [Hibernate, JavaScript, Java] |
2. Example : Remove Elements from HashSet using Iterator
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
package com.kscodes.sampleproject; import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class HashSetRemoveExample { public static void main(String[] args) { Set<String> hashSet = new HashSet<>(); hashSet.add("Java"); hashSet.add("Spring"); hashSet.add("Hibernate"); hashSet.add("JavaScript"); System.out.println("HashSet before removing any element :: " + hashSet.toString()); Iterator<String> iterator = hashSet.iterator(); while (iterator.hasNext()) { iterator.next(); iterator.remove(); } System.out.println("Removed All elements from HashSet :: " + hashSet.toString()); } } |
Output
1 2 |
HashSet before removing any element :: [Hibernate, Spring, JavaScript, Java] Removed All elements from HashSet :: [] |