Course contentsShow
← Java
Lesson 1143 of 2,87026. Map ImplementationsFree lesson

Insertion Order Mode

Learn how LinkedHashMap preserves insertion order, making iteration order match the order keys were added.

Insertion Order Mode

What you'll learn: How LinkedHashMap's default insertion order mode makes iteration predictable by preserving the sequence in which keys were added.

The Core Idea

When you create a LinkedHashMap without special parameters, it operates in insertion order mode. This means that when you iterate through the map's keys, values, or entries, you'll see them in exactly the same order they were first added to the map—regardless of their hash codes or natural ordering.

Think of it like a guest book at a wedding: people sign in the order they arrive, and when you read through it later, you see their names in arrival order, not alphabetical order.

How It Works

Unlike a regular HashMap where iteration order is essentially random (based on hash bucket positions), LinkedHashMap maintains a doubly-linked list connecting all entries. When you put a new key-value pair:

  1. The entry goes into the appropriate hash bucket (just like HashMap)
  2. The entry is also linked to the end of the insertion-order chain

This dual structure gives you O(1) average-case performance for get, put, and remove operations (thanks to the hash table), while guaranteeing predictable iteration (thanks to the linked list).

Why This Matters

Insertion order mode is useful when you need:

  • Predictable, reproducible iteration
  • To preserve the chronological sequence of additions
  • Cache-like behavior (when combined with access order mode—but that's a future lesson!)

Key Takeaway: LinkedHashMap's insertion order mode preserves and iterates entries in the exact sequence they were added, combining HashMap's performance with predictable ordering.