Java ProgramsCollectionsLinkedHashMap Example

LinkedHashMap Example in Java

beginner·  Collections  ·  Map

Problem

A LinkedHashMap keeps its entries in the exact order they were inserted, unlike a plain HashMap, whose iteration order isn't guaranteed at all.

Add several entries to a LinkedHashMap in a specific order and show that iterating it always visits them in that same order.

Input
put(Banana, 2), put(Apple, 5), put(Cherry, 3)
Output
Banana: 2, Apple: 5, Cherry: 3

Java Program

Java
import java.util.LinkedHashMap; import java.util.Map; public class LinkedHashMapExample { public static void main(String[] args) { LinkedHashMap<String, Integer> scores = new LinkedHashMap<>(); scores.put("Banana", 2); scores.put("Apple", 5); scores.put("Cherry", 3); for (Map.Entry<String, Integer> entry : scores.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } } }

Output

Banana: 2 Apple: 5 Cherry: 3

Core Logic

LinkedHashMap keeps an internal linked list threading through its entries in the order they were added, alongside the usual hash table structure, so iteration always follows that same order.

How It Works
  1. 1new LinkedHashMap<String, Integer>() creates a map that behaves like a HashMap for lookups, but also remembers insertion order.
  2. 2put("Banana", 2), put("Apple", 5), and put("Cherry", 3) insert entries in that exact order.
  3. 3Iterating with entrySet() visits Banana, then Apple, then Cherry — the same order they were inserted in, not alphabetical or any other order.
  4. 4A plain HashMap holding the exact same three entries would make no such promise — its iteration order could come out differently, and isn't required to match insertion order at all.
Even though Apple would sort before Banana alphabetically, the map still prints Banana first, since it was inserted first.
💡

Key Point: LinkedHashMap sits between HashMap and TreeMap — it doesn't sort entries the way TreeMap does, but unlike HashMap, its iteration order is fully predictable: always insertion order.

Complexity
Time Complexity: O(1)Space Complexity: O(n)

Why: put() and get() cost O(1) on average, the same as HashMap, with a small constant overhead to maintain the insertion-order linked list; the map holds up to n entries.

Key Concepts

LinkedHashMapinsertion orderHashMap contrast

Related Programs