Java LinkedHashMap Guide: Uses & Examples

LinkedHashMap is a subclass of HashMap that maintains a doubly linked list internally to keep track of the order in which elements are inserted or accessed (sorting based on the order specified in the constructor parameter).

LinkedHashMap has the capability to maintain the order of elements as they are inserted or accessed, making it very useful in certain scenarios such as the LRU caching algorithm, which typically utilizes LinkedHashMap for implementation.

Commonly used methods of LinkedHashMap include put, get, remove, which are similar to HashMap, but can maintain the order of elements. LinkedHashMap also provides additional methods such as entrySet, keySet, values, that are used to retrieve elements in LinkedHashMap.

import java.util.LinkedHashMap;

public class TestLinkedHashMap {
    public static void main(String[] args) {
        LinkedHashMap<String, Integer> linkedHashMap = new LinkedHashMap<>();

        linkedHashMap.put("apple", 1);
        linkedHashMap.put("banana", 2);
        linkedHashMap.put("orange", 3);

        for (String key : linkedHashMap.keySet()) {
            System.out.println(key + " : " + linkedHashMap.get(key));
        }
    }
}

The above code demonstrates the basic usage of LinkedHashMap, storing elements in the order they were inserted and preserving this order during traversal.

bannerAds