Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

LinkedHashMap

A map that remembers the insertion order of keys.

Available since: Java 1.4

Syntax

public class LinkedHashMap<K, V> extends HashMap<K, V> implements SequencedMap<K, V>

Examples

Iteration order matches insertion order:

void main() {
    Map<String, Integer> steps = new LinkedHashMap<>();
    steps.put("download", 3);
    steps.put("install", 5);
    steps.put("configure", 2);
    IO.println(steps);
}

Output:

{download=3, install=5, configure=2}

The first and the last pair (Java 21):

void main() {
    var map = new LinkedHashMap<String, Integer>();
    map.put("a", 1);
    map.put("b", 2);
    map.put("c", 3);
    IO.println(map.firstEntry() + " " + map.lastEntry());
    IO.println(map.reversed());
}

Output:

a=1 c=3
{c=3, b=2, a=1}

Notes

Calling put() again for an existing key does not change its position. The constructor new LinkedHashMap<>(16, 0.75f, true) switches to access order — the basis of a simple LRU cache. Since Java 21 it implements SequencedMap: firstEntry(), lastEntry(), pollFirstEntry(), reversed().

See also

  • HashMap — A map backed by a hash table: fast lookup by key, no guaranteed order.
  • TreeMap — A map whose keys are always sorted.
  • LinkedHashSet — A set that remembers the insertion order of elements.

Related recipes

In the tutorial

  • Maps: Map and HashMap — Maps in Java: key-value pairs, put and get, getOrDefault, counting with merge, TreeMap and LinkedHashMap.

Thanks for reading!

Donate to the site — we work hard for you.