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:
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
| Operation | Time Complexity | Notes |
|---|---|---|
add(e) | O(1) average | Updates hash bucket and appends to linked list |
contains(e) | O(1) average | Direct hash lookup |
remove(e) | O(1) average | Unlinks node and removes from bucket |
- Memory Overhead: Slightly higher than
HashSetdue to maintaining two pointer references (beforeandafter) per entry. - Null Handling: Permits exactly one
nullelement, identical toHashSet.