Java > Java Collections Framework > List, Set, and Map Interfaces > LinkedHashMap

LinkedHashMap Example: Maintaining Insertion Order

LinkedHashMap is a subclass of HashMap that maintains the order in which keys were inserted. This example demonstrates how LinkedHashMap preserves insertion order and how it can be useful.

Basic LinkedHashMap Usage

This code snippet demonstrates the basic operations of a LinkedHashMap, including insertion, iteration, retrieval, checking for key existence, and removal. The output will show that the elements are iterated in the same order they were inserted. The example utilizes the java.util.LinkedHashMap and java.util.Map classes.

import java.util.LinkedHashMap;
import java.util.Map;

public class LinkedHashMapExample {

    public static void main(String[] args) {
        // Creating a LinkedHashMap
        LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<>();

        // Adding key-value pairs
        linkedHashMap.put("Apple", "Red");
        linkedHashMap.put("Banana", "Yellow");
        linkedHashMap.put("Orange", "Orange");
        linkedHashMap.put("Grape", "Purple");

        // Iterating over the LinkedHashMap.  The order is preserved.
        System.out.println("LinkedHashMap contents:");
        for (Map.Entry<String, String> entry : linkedHashMap.entrySet()) {
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }

        // Accessing elements by key
        String color = linkedHashMap.get("Banana");
        System.out.println("\nColor of Banana: " + color);

        // Checking if a key exists
        boolean containsKey = linkedHashMap.containsKey("Orange");
        System.out.println("\nContains key 'Orange': " + containsKey);

        // Removing an element
        linkedHashMap.remove("Apple");
        System.out.println("\nLinkedHashMap after removing 'Apple':");
        for (Map.Entry<String, String> entry : linkedHashMap.entrySet()) {
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }
    }
}

Concepts Behind the Snippet

LinkedHashMap extends HashMap and adds the capability to maintain insertion order or access order. This is achieved using a doubly-linked list running through all of its entries. It provides predictable iteration order, which is not guaranteed by HashMap. When 'accessOrder' is set to true in the constructor, the LinkedHashMap will maintain access order. Every get or put operation will move the accessed element to the end of the list.

Real-Life Use Case

A practical application of LinkedHashMap is implementing a Least Recently Used (LRU) cache. By setting 'accessOrder' to true and overriding the removeEldestEntry() method, you can automatically evict the least recently used entries when the cache reaches its maximum capacity. This is very useful in web servers or database caching scenarios.

Best Practices

  • Consider the memory overhead when using LinkedHashMap, as it requires more memory than HashMap due to the doubly-linked list.
  • When choosing between HashMap and LinkedHashMap, consider whether maintaining order is a strict requirement. If order is not important, HashMap offers slightly better performance.
  • When implementing an LRU cache, ensure that the removeEldestEntry() method is correctly implemented to maintain the desired cache size.

Interview Tip

Be prepared to discuss the differences between HashMap and LinkedHashMap, including their performance characteristics and use cases. Explain how LinkedHashMap maintains order and how it can be used to implement an LRU cache. Also understand the difference between insertion order and access order.

When to Use Them

Use LinkedHashMap when you need to maintain the order of elements in which they were inserted or accessed. This is particularly useful when the iteration order matters, such as in configuration files, caching mechanisms, or situations where you want to process elements in a specific sequence.

Memory Footprint

LinkedHashMap has a larger memory footprint compared to HashMap because it stores additional pointers to maintain the doubly-linked list. This can be a significant consideration when dealing with large datasets. Each entry stores pointers to the next and previous entry which increases the memory usage in comparison to HashMap.

Alternatives

  • HashMap: If order doesn't matter and performance is critical.
  • TreeMap: If you need elements to be sorted by keys. Requires keys to implement the Comparable interface or to provide a Comparator.
  • ConcurrentHashMap: Thread-safe implementation for concurrent environments.

Pros

  • Predictable iteration order (insertion order or access order).
  • Suitable for implementing LRU caches.
  • Provides better performance than TreeMap when sorting is not required.

Cons

  • Higher memory overhead compared to HashMap.
  • Slightly slower performance than HashMap for basic operations (insertion, retrieval, deletion) due to the overhead of maintaining the linked list.

FAQ

  • What is the difference between HashMap and LinkedHashMap?

    HashMap does not guarantee any particular order of elements, while LinkedHashMap maintains either the order in which elements were inserted or the order in which they were accessed (LRU). LinkedHashMap is slightly slower and requires more memory than HashMap.
  • How can I implement an LRU cache using LinkedHashMap?

    Create a LinkedHashMap with accessOrder set to true in the constructor. Override the removeEldestEntry() method to return true when the cache size exceeds a certain limit. This will automatically remove the least recently used entry.
  • When should I use LinkedHashMap over TreeMap?

    Use LinkedHashMap when you need to maintain insertion order or access order, and you don't require the elements to be sorted by their keys. TreeMap provides sorted order based on keys, which incurs a performance cost if sorting is not necessary.