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:
xxxxxxxxxx
1
myHashSet.remove(item);
In this example, we use remove()
method to delete selected item from the letters
HashSet.
xxxxxxxxxx
1
import java.util.*;
2
3
public class Example {
4
5
public static void main(String[] args) {
6
Set<String> letters = new HashSet<>();
7
8
letters.add("A");
9
letters.add("B");
10
letters.add("C");
11
12
System.out.println("Before: " + letters); // [A, B, C]
13
14
letters.remove("C"); // removes item
15
16
System.out.println("After: " + letters); // [A, B]
17
}
18
}
Output:
xxxxxxxxxx
1
Before: [A, B, C]
2
After: [A, B]
In this example, we use clear()
method to remove all items from the letters
HashSet.
xxxxxxxxxx
1
package hashsetOperations;
2
3
import java.util.*;
4
5
public class Example {
6
7
public static void main(String[] args) {
8
Set<String> letters = new HashSet<>();
9
10
letters.add("A");
11
letters.add("B");
12
letters.add("C");
13
14
System.out.println("Before: " + letters); // [A, B, C]
15
16
letters.clear(); // removes all items
17
18
System.out.println("After: " + letters); // []
19
}
20
}
Output:
xxxxxxxxxx
1
Before: [A, B, C]
2
After: []