Attic
CollectionsSets

LinkedHashSet

Doubly-linked hash buckets, maintaining insertion order, and first-seen deduplication

LinkedHashSet<E> extends HashSet by threading a doubly-linked list through all its entries. While it inherits hash table lookup speeds, iteration always visits elements in the exact order they were inserted.


Order-Preserving Deduplication

The canonical use case for LinkedHashSet is removing duplicates while guaranteeing that the first-seen order is preserved:

DeduplicationDemo.java
List<String> listWithDuplicates = List.of("b", "a", "b", "c", "a");

// Deduplicate while preserving first-seen insertion order
Set<String> uniqueOrdered = new LinkedHashSet<>(listWithDuplicates);

System.out.println(uniqueOrdered); // [b, a, c]

Complexity & Overhead

OperationTime ComplexityNotes
add(e)O(1) averageUpdates hash bucket and appends to linked list
contains(e)O(1) averageDirect hash lookup
remove(e)O(1) averageUnlinks node and removes from bucket
  • Memory Overhead: Slightly higher than HashSet due to maintaining two pointer references (before and after) per entry.
  • Null Handling: Permits exactly one null element, identical to HashSet.

On this page