<code>HashSet</code> in Java β Unique Elements, O(1) Lookup
HashSet stores unique elements with average O(1) add, contains and remove. Internally it's a HashMap where the values are a dummy marker. Like HashMap, iteration order is not defined.
Basics
var seen = new HashSet<String>();
seen.add("alpha");
seen.add("alpha"); // duplicate β returns false, set unchanged
seen.size(); // 1
seen.contains("alpha"); // true
seen.remove("alpha");
Deduplication one-liner
var unique = new LinkedHashSet<>(withDuplicates); // keeps insertion order
var uniqueFast = new HashSet<>(withDuplicates); // faster, random order
Set operations
var a = new HashSet<>(Set.of(1, 2, 3));
var b = new HashSet<>(Set.of(2, 3, 4));
// Union
var union = new HashSet<>(a);
union.addAll(b); // {1, 2, 3, 4}
// Intersection
var intersect = new HashSet<>(a);
intersect.retainAll(b); // {2, 3}
// Difference
var diff = new HashSet<>(a);
diff.removeAll(b); // {1}
Elements must obey equals/hashCode
Like HashMap, custom elements need correct equals and hashCode β or duplicates slip in. Use records.
HashSet vs alternatives
| Need | Pick |
|---|---|
| Default set | HashSet |
| Insertion-order iteration | LinkedHashSet |
| Sorted | TreeSet |
| Thread-safe | ConcurrentHashMap.newKeySet() or CopyOnWriteArraySet |
| Immutable, small | Set.of(...) |
Common mistakes
- Custom element without
hashCodeβ duplicates aren't detected. Use a record. - Expecting insertion order β use
LinkedHashSet. - Using
HashSet.containson aListβList.containsis O(n). If you check many times, convert to aSetonce.
Related
Pillar: Java collections. Siblings: TreeSet, HashMap.