Java LinkedHashMap

Introduction

The Java LinkedHashMap class is a popular implementation of the Map interface in the Java Collections Framework. It combines the fast performance of HashMap with the ability to maintain the insertion order of key-value pairs. This makes it an excellent choice when you need predictable iteration order while still benefiting from efficient lookup, insertion, and deletion operations.

The LinkedHashMap class belongs to the java.util package and extends the HashMap class. Internally, it uses a hash table along with a doubly linked list that connects all entries in the order they were inserted.

LinkedHashMap allows one null key and multiple null values.

LinkedHashMap is commonly used in applications such as LRU (Least Recently Used) caches, navigation menus, order tracking systems, configuration settings, user preferences, shopping carts, and report generation, where maintaining the order of entries is important.

What is Java LinkedHashMap?

A LinkedHashMap is a collection that stores data in the form of key-value pairs while preserving the insertion order of entries.

  • Each key must be unique.
  • Duplicate keys are not allowed.
  • Values can be duplicated.
  • The order of insertion is maintained during iteration.

Example:

Key Value
101 Rahul
102 Amit
103 Neha

Output while iterating:


101=Rahul
102=Amit
103=Neha

Even if the internal hash table changes, the iteration order remains the same.

Java LinkedHashMap Hierarchy


Object
   │
AbstractMap
   │
HashMap
   │
LinkedHashMap

The LinkedHashMap class implements:

The LinkedHashMap class implements:

  • Map
  • Cloneable
  • Serializable

Features of Java LinkedHashMap

Some important features of LinkedHashMap are:

  • Stores data as key-value pairs
  • Maintains insertion order
  • Allows one null key
  • Allows multiple null values
  • Fast lookup and insertion
  • Dynamic size
  • Supports Generics
  • Backed by a hash table and doubly linked list
  • Can maintain access order for cache implementations

Syntax

Import Statement


import java.util.LinkedHashMap;

or


import java.util.*;

Creating a LinkedHashMap


LinkedMap<Integer, String> students = new HashMap<>();

Using the Map interface:


Map<Integer, String> students = new HashMap<>();

Programming to the Map interface is considered a best practice.

Constructors of LinkedHashMap

1. Default Constructor


LinkedMap<Integer, String> Map = new HashMap<>();

Creates an empty LinkedHashMap with the default capacity and load factor.

2. Constructor with Initial Capacity


LinkedMap<Integer, String> Map = new HashMap<>(20);

Creates a LinkedHashMap with an initial capacity of 20.

3. Constructor with Capacity and Load Factor


LinkedMap<Integer, String> Map = new HashMap<>(20, 0.75f);

Creates a LinkedHashMap with:

  • Initial Capacity = 20
  • Load Factor = 0.75

4. Constructor with Access Order


LinkedMap<Integer, String> Map = new HashMap<>(20, 0.75f,true);

When the third parameter is true, the map maintains access order instead of insertion order. This feature is useful for implementing LRU caches.

5. Constructor from Another Map


Map<Integer, String> Map1 = new HashMap<>();
map1.put(101, "Rahul");
map1.put(102, "Amit");

LinkedMap<Integer, String> Map2 = new HashMap<>(Map1);

System.out.println(map2);

Output

{101=Rahul, 102=Amit}

Common Methods of LinkedHashMap

Method Description
get() Returns the value associated with a key
remove() Removes a key-value pair
containsKey() Checks if a key exists
containsValue() Checks if a value exists
size() Returns the number of key-value pairs
isEmpty() Checks whether the map is empty
clear() Removes all mappings
keySet() Returns all keys
values() Returns all values
entrySet() Returns all key-value pairs

Example 1: Creating a LinkedHashMap


import java.util.*;

public class LinkedHashMapExample {

    public static void main(String[] args) {

     LinkedHasMap<Integer, String> students = new HashMap<>();

        students.put(101, "Rahul");
        students.put(102, "Amit");
        students.put(103, "Neha");

        System.out.println(students);
    }
}

Output

{101=Rahul, 102=Amit, 103=Neha}

The insertion order is preserved.

Example 2: Updating a Value


import java.util.*;

public class UpdateExample {

    public static void main(String[] args) {

        LinkedHasMap<Integer, String> students = new HashMap<>();

        students.put(101, "Rahul");

        students.put(101, "Rohan");

        System.out.println(students);
    }
}

Output

{101=Rohan}

The value is updated because duplicate keys are not allowed.

Example 3: Retrieving a Value


import java.util.*;

public class GetExample {

    public static void main(String[] args) {

        LinkedHasMap<Integer, String> students = new HashMap<>();

        students.put(101, "Rahul");

        System.out.println(students.get(101));
    }
}

Output

Rahul

Example 4: Removing an Entry


import java.util.*;

public class RemoveExample {

    public static void main(String[] args) {

         LinkedHasMap<Integer, String> students = new HashMap<>();

        students.put(101, "Rahul");
        students.put(102, "Amit");

        students.remove(102);

        System.out.println(students);
    }
}

Output

{101=Rahul}

Example 5: Iterating Through a LinkedHashMap


import java.util.*;

public class LoopExample {

    public static void main(String[] args) {

       LinkedHasMap<Integer, String> students = new HashMap<>();

        students.put(101, "Rahul");
        students.put(102, "Amit");
        students.put(103, "Neha");

        for  Map<Integer, String> entry = new HashMap<>(); {

            System.out.println(entry.getKey()
                    + " : "
                    + entry.getValue());

        }
    }
}

Output

101 : Rahul
102 : Amit
103 : Neha

Entries are printed in the same order they were inserted.

How LinkedHashMap Works Internally

LinkedHashMap extends HashMap and internally combines:

  • A hash table for fast lookup.
  • A doubly linked list to maintain the order of entries.

The process is:

  1. The key’s hashCode() determines the bucket.
  2. The key-value pair is stored in the hash table.
  3. A doubly linked list connects all entries.
  4. During iteration, entries are returned according to insertion order (or access order if enabled).

This design provides both speed and predictable iteration.

Feature HashMap LinkedHashMap TreeMap
Duplicate Keys No No No
Duplicate Values Yes Yes Yes
Insertion Order No Yes No
Sorted Keys No No Yes
Null Key One One No
Null Values Yes Yes Yes
Internal Structure Hash Table Hash Table + Linked List Red-Black Tree
Performance Fastest Fast Slower

Time Complexity

Operation Time Complexity
put() O(1) Average
remove() O(1) Average
containsKey() O(1) Average
containsValue() O(n)

LinkedHashMap is only slightly slower than HashMap because it maintains a linked list.

Real-life Example

Imagine you’re building an online order tracking system.

Orders are received in the following sequence:

Key Value
101 Rahul
102 Amit
103 Neha

Using a LinkedHashMap, reports display orders exactly as they were received:


1001=Rahul
1002=Amit
1003=Neha

Other real-world applications include:

  • Shopping cart systems
  • Recently viewed products
  • Navigation menus
  • User preferences
  • Configuration settings
  • Report generation
  • Browser history
  • LRU cache implementation

Advantages of Java LinkedHashMap

  • Maintains insertion order
  • Fast insertion and retrieval
  • Allows one null key
  • Allows multiple null values
  • Dynamic resizing
  • Supports Generics
  • Suitable for ordered data
  • Can be configured for access-order traversal

Limitations of Java LinkedHashMap

  • Slightly slower than HashMap
  • Uses more memory because of the linked list
  • Does not sort keys
  • Not synchronized
  • Duplicate keys are not allowed

Common Mistakes

1. Expecting Sorted Keys

Incorrect assumption:


map.put(30, "C");
map.put(10, "A");
map.put(20, "B");

Output:

30=C
10=A
20=B

LinkedHashMap maintains insertion order, not sorted order.

2. Adding Duplicate Keys


map.put(101, "Rahul");
map.put(101, "Amit");

Output:

{101=Amit}

The second value replaces the first.

3. Forgetting Generics

Incorrect:


LinkedHashMap map = new LinkedHashMap();

Correct:


LinkedHasMap<Integer, String> students = new HashMap<>();

4. Assuming It Is Thread-Safe

LinkedHashMap is not synchronized. For concurrent access, use external synchronization or consider ConcurrentHashMap if ordering is not required.

5. Ignoring Access-Order Constructor

Many developers are unaware that LinkedHashMap can maintain access order, making it useful for implementing cache eviction strategies like LRU.

Best Practices

  • Program to the Map interface.

Map<Integer, String> students = new HashMap<>();
  • Use LinkedHashMap when insertion order matters.
  • Use HashMap for maximum performance if order is not important.
  • Use TreeMap when sorted keys are required.
  • Always use Generics for type safety.
  • Use the access-order constructor for cache implementations.
  • Override equals() and hashCode() correctly when using custom objects as keys.

Conclusion

The Java LinkedHashMap class is an excellent choice when your application requires fast key-value storage along with predictable iteration order. By combining the efficiency of a hash table with the ordering capabilities of a doubly linked list, it offers a perfect balance between performance and usability.

Related Java Tutorials