EN
Java - remove items from HashSet
0
points
In this article, we would like to show you how to remove items from the HashSet in Java.
Quick solution:
myHashSet.remove(item);
1. Remove selected items
In this example, we use remove()
method to delete selected item from the letters
HashSet.
import java.util.*;
public class Example {
public static void main(String[] args) {
Set<String> letters = new HashSet<>();
letters.add("A");
letters.add("B");
letters.add("C");
System.out.println("Before: " + letters); // [A, B, C]
letters.remove("C"); // removes item
System.out.println("After: " + letters); // [A, B]
}
}
Output:
Before: [A, B, C]
After: [A, B]
2. Remove all items
In this example, we use clear()
method to remove all items from the letters
HashSet.
package hashsetOperations;
import java.util.*;
public class Example {
public static void main(String[] args) {
Set<String> letters = new HashSet<>();
letters.add("A");
letters.add("B");
letters.add("C");
System.out.println("Before: " + letters); // [A, B, C]
letters.clear(); // removes all items
System.out.println("After: " + letters); // []
}
}
Output:
Before: [A, B, C]
After: []