Course contentsShow
← Java
Lesson 983 of 2,87023. Collections Framework OverviewFree lesson

LinkedHashSet and LinkedHashMap: Preserving Insertion Order

Using linked variants when you need hash performance but also predictable iteration order.

LinkedHashSet and LinkedHashMap: Preserving Insertion Order

What you'll learn: How to get hash-table performance while maintaining predictable iteration order using linked variants.

The Best of Both Worlds

You've learned that HashSet and HashMap offer excellent performance but iterate in seemingly random order. You've also seen that TreeSet and TreeMap provide sorted order but at a higher performance cost. What if you need fast operations and predictable iteration order?

Enter LinkedHashSet and LinkedHashMap: they maintain insertion order while keeping hash-table speed.

How They Work

Both classes use a hash table for storage (like their non-linked counterparts) but add a doubly-linked list running through all entries. This list tracks the order in which elements were inserted.

Think of it like a library with two organizational systems: a hash-based index for fast lookup and a timeline board showing books in the order they arrived.

When to Use Them

Use LinkedHashSet when you need:

  • Fast add(), contains(), and remove() operations
  • Predictable iteration order matching insertion sequence
  • No duplicate elements

Use LinkedHashMap when you need:

  • Fast key-based lookups
  • Iteration over entries in the order keys were first inserted
  • Optional access-order mode (for caching scenarios)

The Performance Trade-Off

These linked variants are slightly slower than plain HashSet/HashMap (due to maintaining the linked list) but significantly faster than TreeSet/TreeMap. The iteration order is insertion-based, not natural/sorted order.

Key Takeaway: Use LinkedHashSet and LinkedHashMap when you need hash-table performance but also want predictable, insertion-ordered iteration—a practical middle ground between unordered hash collections and sorted tree collections.