← The curriculum
§ 6.08 · Data Structures in Java

HashSet and LinkedHashMap — uniqueness and order

Deduping in O(1), preserving insertion order, and building an LRU cache in 6 lines.

Intermediate · 22 minute read
Try it yourself
Live Java · editable

Runs on a sandboxed JVM via the public Piston API. Edit the code and hit Run.

§ 6.08.01

HashSet is a HashMap in disguise

Internally, HashSet stores keys in a HashMap with a placeholder value. Membership checks and inserts are O(1) on average, but iteration order is unspecified. If you're writing if (!list.contains(x)) list.add(x), replace it with set.add(x) — the set's add returns true only if the element is new.

§ 6.08.02

The three flavors of Set

HashSet — fastest, no order. LinkedHashSet — same speed with a doubly-linked list threaded through entries for predictable insertion-order iteration. TreeSet — O(log n) but sorted, with first, last, floor, and ceiling. Pick by the guarantee you actually need.

§ 6.08.03

LinkedHashMap preserves order

LinkedHashMap threads a doubly-linked list through the entries. In insertion-order mode (default), iteration yields entries in the order they were first added — great for stable serialization. In access-order mode (accessOrder = true), every get or put moves the entry to the tail, which is exactly what you want for LRU.

§ 6.08.04

An LRU cache in six lines

Extend LinkedHashMap, turn on access order, and override removeEldestEntry to evict when the map grows past your target size. That's a fully functional LRU cache in a handful of lines — no external library, no thread synchronization to worry about in single-threaded contexts.

Example
Live Java · editable

Runs on a sandboxed JVM via the public Piston API. Edit the code and hit Run.

§ 6.08.05

Dedupe idioms

Convert a list to a set and back: new ArrayList<>(new LinkedHashSet<>(list)) dedupes while preserving order. Streams: list.stream().distinct().toList() does the same in one line. Both rely on correct equals/hashCode on the elements.

§ 6.08.06

Thread safety

Neither HashSet nor LinkedHashMap is thread-safe. For concurrent sets, use ConcurrentHashMap.newKeySet(). For a thread-safe LRU cache, reach for Caffeine or Guava — they add proper concurrency, weighting, and expiration.