Java HashSet
A set is a collection that contains no duplicates. Add the same element twice and the set simply ignores the second one. Sets are perfect for questions like "have I seen this before?", for removing duplicates from data, and for set mathematics such as union and intersection. HashSet is the standard implementation.
Creating and using a set
import java.util.HashSet;
import java.util.Set;
class Main {
public static void main(String[] args) {
Set<String> visited = new HashSet<>();
System.out.println(visited.add("Paris")); // true: added
System.out.println(visited.add("Rome"));
System.out.println(visited.add("Paris")); // false: already there
System.out.println("Size: " + visited.size());
System.out.println(visited.contains("Rome"));
visited.remove("Rome");
System.out.println(visited.contains("Rome"));
}
}true
true
false
Size: 2
true
false
add returns true if the element was new — a handy way to detect duplicates as you go. contains is very fast on a HashSet, even with millions of elements.
Order: HashSet vs. LinkedHashSet vs. TreeSet
Like HashMap, a HashSet has no defined iteration order. Choose another implementation when order matters:
| Implementation | Order | Typical use |
|---|---|---|
HashSet |
unspecified | fastest membership checks |
LinkedHashSet |
insertion order | de-duplicate while keeping order |
TreeSet |
sorted | sorted unique values, ranges |
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
class Main {
public static void main(String[] args) {
List<String> tags = List.of("java", "web", "java", "api", "web", "cloud");
Set<String> inOrder = new LinkedHashSet<>(tags);
Set<String> sorted = new TreeSet<>(tags);
System.out.println(tags);
System.out.println(inOrder);
System.out.println(sorted);
}
}[java, web, java, api, web, cloud]
[java, web, api, cloud]
[api, cloud, java, web]
Passing a collection to a set's constructor is the quickest way to remove duplicates.
Finding duplicates
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
class Main {
public static void main(String[] args) {
int[] ids = {104, 221, 87, 104, 310, 87, 87};
Set<Integer> seen = new HashSet<>();
Set<Integer> duplicates = new TreeSet<>();
for (int id : ids) {
if (!seen.add(id)) {
duplicates.add(id);
}
}
System.out.println("Unique ids: " + seen.size());
System.out.println("Duplicated: " + duplicates);
}
}Unique ids: 4
Duplicated: [87, 104]
Set operations
addAll, retainAll and removeAll implement union, intersection and difference. They modify the set they're called on, so start from a copy:
import java.util.Set;
import java.util.TreeSet;
class Main {
public static void main(String[] args) {
Set<String> alice = new TreeSet<>(Set.of("chess", "hiking", "jazz", "cooking"));
Set<String> bob = new TreeSet<>(Set.of("jazz", "football", "cooking"));
Set<String> union = new TreeSet<>(alice);
union.addAll(bob);
Set<String> common = new TreeSet<>(alice);
common.retainAll(bob);
Set<String> onlyAlice = new TreeSet<>(alice);
onlyAlice.removeAll(bob);
System.out.println("Either: " + union);
System.out.println("Both: " + common);
System.out.println("Only Alice: " + onlyAlice);
}
}Either: [chess, cooking, football, hiking, jazz]
Both: [cooking, jazz]
Only Alice: [chess, hiking]
| Operation | Math | Method |
|---|---|---|
| union | A ∪ B | a.addAll(b) |
| intersection | A ∩ B | a.retainAll(b) |
| difference | A − B | a.removeAll(b) |
| subset test | A ⊆ B | b.containsAll(a) |
Note: Sets decide whether two elements are "the same" with
equalsandhashCode(orcompareToforTreeSet). For your own classes, override those methods — or use arecord, which does it for you.
Test yourself
What does set.add(x) return if x is already in the set?
- true
- false
- null
- It throws an exception
Which set keeps elements in the order they were inserted?
- HashSet
- TreeSet
- LinkedHashSet
- EnumSet
Which method keeps only the elements that are also in another collection?
- addAll
- removeAll
- retainAll
- containsAll