<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

NeedPick
Default setHashSet
Insertion-order iterationLinkedHashSet
SortedTreeSet
Thread-safeConcurrentHashMap.newKeySet() or CopyOnWriteArraySet
Immutable, smallSet.of(...)

Common mistakes

  • Custom element without hashCode β€” duplicates aren't detected. Use a record.
  • Expecting insertion order β€” use LinkedHashSet.
  • Using HashSet.contains on a List β€” List.contains is O(n). If you check many times, convert to a Set once.

Related

Pillar: Java collections. Siblings: TreeSet, HashMap.