LinkedHashSet in Java

LinkedHashSet combines the uniqueness guarantee of HashSet with a doubly-linked list that preserves insertion order during iteration.

LinkedHashSet<E> is a Set implementation that extends HashSet and adds a doubly-linked list running through all entries. This list maintains the order in which elements were first inserted, so iteration always reflects insertion order — unlike HashSet (unpredictable) and TreeSet (sorted order). Performance is nearly identical to HashSet, with a small overhead for maintaining the extra pointers.

How LinkedHashSet Works Internally

LinkedHashSet is built on top of LinkedHashMap in exactly the same way HashSet is built on HashMap. Each element is stored as a key in a LinkedHashMap<E, Object>, where the map's internal doubly-linked list tracks insertion order. The hash-table mechanics (bucketing, treeification, resizing) are identical to HashSet.

Operation Average Worst case
add O(1) O(log n)
remove O(1) O(log n)
contains O(1) O(log n)
Iteration O(n) O(n) — follows list

Key characteristics:

  • No duplicate elements.
  • Iteration order equals insertion order.
  • One null element is permitted.
  • Not thread-safe.
  • Slightly higher memory use than HashSet due to the linked list.

Examples

Insertion-order iteration

import java.util.LinkedHashSet;
import java.util.Set;

public class LinkedHashSetOrder {
    public static void main(String[] args) {
        Set<String> steps = new LinkedHashSet<>();
        steps.add("compile");
        steps.add("test");
        steps.add("package");
        steps.add("deploy");
        steps.add("compile");  // duplicate — ignored, order not changed

        for (String step : steps) {
            System.out.println(step);
        }
        // Output (always in insertion order):
        // compile
        // test
        // package
        // deploy
    }
}

Deduplication while preserving order

import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

public class OrderedDeduplicate {
    public static void main(String[] args) {
        List<String> raw = Arrays.asList("banana", "apple", "banana", "cherry", "apple");
        Set<String> deduped = new LinkedHashSet<>(raw);
        System.out.println(deduped); // [banana, apple, cherry]

        // Convert back to list when a List is needed downstream
        List<String> result = new java.util.ArrayList<>(deduped);
        System.out.println(result.get(0)); // banana
    }
}

Common Mistakes

  1. Using HashSet when order matters. If the business requirement is "process items in the order they were seen", HashSet silently reorders them. Switch to LinkedHashSet for deterministic, insertion-ordered iteration.

  2. Re-inserting to "move to end". LinkedHashSet does not update an element's position when you add it again — the element already exists, so add returns false and the list position stays the same. To move an element to the end, you must remove it first, then add it.

  3. Missing equals/hashCode on custom types. Same as HashSet: without these overrides, duplicate custom objects are inserted separately.

  4. Assuming thread safety. LinkedHashSet is not synchronized. Wrap it with Collections.synchronizedSet(new LinkedHashSet<>()) or use an alternative if concurrent access is required.

  5. Confusing insertion-order with access-order. LinkedHashMap optionally supports access-order (LRU). LinkedHashSet always uses insertion-order — there is no access-order mode.

Best Practices

  • Declare variables as Set<E> to keep implementation details private.
  • Use LinkedHashSet when you need both uniqueness and deterministic iteration order — for example, collecting unique event types in the order they first occurred.
  • When converting a List to deduplicated List while preserving order: new ArrayList<>(new LinkedHashSet<>(list)) is a clean one-liner.
  • Pre-size with new LinkedHashSet<>(expectedCapacity, 0.75f) when the approximate element count is known.
  • Prefer Set.copyOf(linkedHashSet) (Java 10+) for an immutable snapshot — note that Set.copyOf does not preserve order.

Interview Questions

1. What is LinkedHashSet and how does it differ from HashSet?

LinkedHashSet extends HashSet and maintains a doubly-linked list through all entries. The linked list preserves insertion order, so iteration always reflects the order elements were added. HashSet gives no ordering guarantee. Both have O(1) average operations; LinkedHashSet uses slightly more memory per entry.

2. How does LinkedHashSet maintain insertion order?

Internally LinkedHashSet delegates to a LinkedHashMap. LinkedHashMap augments each HashMap entry with before and after pointers that form a doubly-linked list. Adding an element appends it to the tail of this list; removing an element unlinks it. The iterator follows this list rather than the hash-table array.

3. Why does re-adding an existing element not move it to the end?

add calls the backing map's put, which finds the key already present and returns without modifying the entry. The insertion-order linked list therefore retains the element's original position. To reorder, explicitly remove then add.

4. When would you choose LinkedHashSet over TreeSet?

Choose LinkedHashSet when you need O(1) operations and want to preserve insertion order. Choose TreeSet when you need elements in sorted (natural or custom) order and O(log n) operations are acceptable. LinkedHashSet also permits null, while TreeSet does not with natural ordering.

5. Is LinkedHashSet thread-safe?

No. Wrap it with Collections.synchronizedSet(new LinkedHashSet<>()) for coarse-grained locking, or reconsider the data structure if high concurrency is required.

6. What happens to LinkedHashSet iteration order if elements are removed and re-added?

The element first appears in the iteration at the position of its original insertion. If you remove it and add it again, it is appended to the end of the linked list, so it appears last in subsequent iterations.

7. How is the fail-fast behaviour of LinkedHashSet's iterator triggered?

LinkedHashSet inherits the fail-fast iterator from LinkedHashMap. The iterator records the map's modCount at creation. Any structural modification (add or remove) after the iterator is created increments modCount, causing the iterator's next next() call to throw ConcurrentModificationException.

Summary

  • LinkedHashSet guarantees uniqueness and preserves insertion order during iteration.
  • It is backed by LinkedHashMap, which maintains a doubly-linked list through all entries.
  • Time complexity matches HashSet — O(1) average — with a small constant overhead per entry.
  • Use it when you need a deduplicated collection where order of first appearance must be retained.
  • It is not thread-safe; synchronize externally when used across multiple threads.

Continue Learning

Previous: HashSet | Next: TreeSet

Was this guide helpful?

CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.