LinkedHashMap is a Map implementation which maintains the insertion order of its elements. It extends the HashMap class:
public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V>
Just like a HashMap, it allows storing one null key and many null values.
We can use one of the following constructors to create a LinkedHashMap:
LinkedHashMap() //default capacity 16 with load factor of 0.75 LinkedHashMap(Map<? extends K,? extends V> map) LinkedHashMap(int initialCapacity) LinkedHashMap(int initialCapacity, float loadFactor) LinkedHashMap(int initialCapacity, float loadFactor , boolean accessOrder)
The very last constructor also accepts a boolean argument accessOrder.
When we pass true to the accessOrder, we’re instantiating an access-order LinkedHashMap. An access-order LinkedHashMap maintains the access order of elements from the least-recently-used to the most-recently-used, instead of the insertion order.
We can classify a Java LinkedHashMap in two main categories:
Unless stated otherwise, a LinkedHashMap maintains the insertion order of its elements. We can name it as an insertion-order LinkedHashMap.
Let’s look at an example:
@Test public void insertionOrderLinkedHashMap() { LinkedHashMap<Integer, String> map = new LinkedHashMap<>(); map.put(1, "A"); map.put(2, "B"); map.put(3, "C"); assertEquals("[1, 2, 3]", map.keySet().toString()); map.get(2); // accessing element assertEquals("[1, 2, 3]", map.keySet().toString()); //still maintains insertion order }
When we use the constructor: LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder) and pass a true value to the accessOrder argument, we’ll have an access-order LinkedHashMap.
Let’s see how an access-order LinkedHashMap actually works:
@Test public void accessOrderLinkedHashMap() { LinkedHashMap<Integer, String> map = new LinkedHashMap<>(16, 0.75f, true); map.put(1, "A"); map.put(2, "B"); map.put(3, "C"); assertEquals("[1, 2, 3]", map.keySet().toString()); map.get(2); // accessing element assertEquals("[1, 3, 2]", map.keySet().toString()); }
On accessing the element with the key as 2, it moved to the very last position. Clearly, the elements are ordered based on their access order from the least recent to the most recent.
Let’s explore the popular methods:
Let’s now try out a few of these methods:
Map<Integer, String> map = new LinkedHashMap<>(); map.put(1, "A"); map.put(2, "B"); map.forEach((k, v) -> System.out.println(k + ":" + v)); System.out.println(map.size()); System.out.println(map.containsKey(1)); System.out.println(map.get(1)); map.remove(1); for(Map.Entry<Integer, String> entry : map.entrySet()) { System.out.println("Key=" + entry.getKey() + ", Value=" + entry.getValue()); }
In this quick article, we looked at what a LinkedHashMap is and how can we instantiate and use it.