Java LinkedHashMap: When to and when not to use LinkedHashMap

LinkedHashedMap has some useful properties. It combines the best of both LinkedList and Hashmap.

From the HashMap camp, it brings the following advantages:
1) Faster access times O(1)
2) Faster add and removal times O(1)

From the LinkedList camp, it brings the following advantages:
1) Maintain insertion order
2) Iterate through the elements in insertion order

But LinkedHashMap is not perfect and it has some flaws which are not very obvious.
1) You don’t have direct control over the order of elements
2) Accessing value by index is O(n)

No direct control over order of elements

I have discussed about this problem in the following blog post.

Poor performance when accessing value by index

Sadly LinkedHashMap doesn’t expose the LinkedList. The only to access the elements is through entrySet or keySet. Set interface doesn’t support accessing elements by index either. So, the users have to resort to creating an Array from the Set. This incurs a performance hit.

Instead you can just iterate through the set to the required position. This will have same performance stats as LinkedList (O(n)) but not HashMap (O(1)).

Java LinkedHashMap: Changing the order of items

The answer is you can’t change the order of elements in a LinkedHashMap in Java directly. This means that you don’t have direct control over the order of elements in a LinkedHashMap. It has the ability to only maintain the insertion order or access order. There are no methods or iterators through which you can insert an element at a desired position. The only possible way to insert an element into LinkedHashMap is through put method inherited from Map interface.

LinkedHashMap<String, Integer> map = new LinkedHashMap<String, Integer>();
map.put("One", 1);

This gives you no way to insert at a particular position. The entrySet method returns you the ordered Set of its entries. But you cannot add a new element into the LinkedHashMap through the entrySet because the LinkedHashMap.Entry class is private to LinkedHashMap and is invisible outside. So there is no way to create a custom entry instance and insert it into the entrySet.

So, if you are using LinkedhashMap for

  1. Faster access times (Offered by HashMap) O(1)
  2. Faster add and removal times (Offered by HashMap) O(1)
  3. Maintaining order of insertion (Offered by LinkedList)
  4. Iterating through order of insertion (Offered by LinkedList)

you made the right choice. But if your application demands that the order of elements may change at some point in time after insertion, LinkedHashMap is not your option.