
Since in LRU or Least Recently Used Cache, oldest non accessed entry is removed, which is the head of the doubly linked list maintained by LinkedHashMap.Ħ. When a particular entry is accessed, it moves towards end of the doubly linked list, maintained by LinkedHashMap.Ĥ) LinkedHashMap can be used to create LRU cache in Java.

Linked hashmap update#
For example, if you already have mapping for a key, and want to update it's value by calling put(key, newValue), insertion order of LinkedHashMap will remain same.ģ) Access order is affected by calling get(key), put(key, value) or putAll(). That's all about the difference between LinkedHashMap and HashMap in Java.ĭifference between TreeSet and HashSet in Javaĭifference between HashMap and ArrayList in Javaįew things to note, while using LinkedHashMap in Java :ġ) Default ordering provided by LinkedHashMap is the order on which key is inserted, known as insertion order, but LinkedHashMap can be created with another ordering called access ordrder, which is defined by accessing entries.Ģ) Re-entering a mapping, doesn't alter insertion order of LinkedHashMap. Given the insertion order guarantee of LinkedHashMap, It's a good compromise between HashMap and TreeMap in Java because with TreeMap you get increased cost of iteration due to sorting and performance drops on to log(n) level from constant time. If overridden, an implementation can return true to remove the oldest entry, when a new entry is added. LinkedHashMap also provides a method called removeEldestEntry(), which is protected, and default implementation return false. either insertion order or access order.Ħ. Iterator of LinkedHashMap returns elements in the order e.g. Since in LRU or Least Recently Used Cache, the oldest non accessed entry is removed, which is the head of the doubly linked list maintained by LinkedHashMap.ĥ. LinkedHashMap can be used to create an LRU cache in Java.

When a particular entry is accessed, it moves towards the end of the doubly linked list, maintained by LinkedHashMap.Ĥ. Access order is affected by calling get(key), put(key, value), or putAll(). For example, if you already have mapping for a key, and want to update its value by calling put(key, newValue), the insertion order of LinkedHashMap will remain the same.ģ. Re-entering a mapping, doesn't alter the insertion order of LinkedHashMap. Default ordering provided by LinkedHashMap is the order on which key is inserted, known as insertion order, but LinkedHashMap can be created with another ordering called access order, which is defined by accessing entries.Ģ.
