LinkedHashMap in Java – Map With Order

LinkedHashMap in Java is also one of the implementation of the Map interface. How it differs from the other implementation HashMap is that unlike HashMap which is unordered, LinkedHashMap is ordered. LinkedHashMap class in Java also extends HashMap apart from implementing Map interface.

LinkedHashMap maintains a doubly-linked list running through all of its entries which defines the iteration ordering. There are two options for ordering-

  • Insertion ordering– The order in which keys were inserted into the Map. Insertion ordering is default ordering for the LinkedHashMap in Java.
  • Access ordering– The order in which its entries were last accessed, from least-recently accessed to most-recently. There is a special constructor for creating LinkedHashMap with access ordering.

Features of LinkedHashMap

Some of the features of the LinkedHashMap in Java which are discussed in this post are as follows-

  1. In LinkedHashMap values may be duplicate but a key has to be unique. If same key is reinserted that doesn’t affect the insertion order.
  2. LinkedHashMap is ordered.
  3. LinkedHashMap permits both null values and null keys. But only single null key is permitted where as there can be multiple null values.
  4. LinkedHashMap in Java is not thread safe.
  5. The iterators returned by all of LinkedHashMap’s “collection view methods” are fail-fast. Which means, if the map is structurally modified at any time after the iterator is created, in any way except through the iterator’s own remove method, the Iterator throws a ConcurrentModificationException.

Java LinkedHashMap constructors

  • LinkedHashMap()– Constructs an empty insertion-ordered LinkedHashMap instance with the default initial capacity (16) and load factor (0.75).
  • LinkedHashMap(int initialCapacity)– Constructs an empty insertion-ordered LinkedHashMap instance with the specified initial capacity and a default load factor (0.75).
  • LinkedHashMap(int initialCapacity, float loadFactor)– Constructs an empty insertion-ordered LinkedHashMap instance with the specified initial capacity and load factor.
  • LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder)– Constructs an empty LinkedHashMap instance with the specified initial capacity, load factor and ordering mode. If accessOrder is passed as true true then access-order, false for insertion-order.
  • LinkedHashMap(Map<? extends K,? extends V> m)– Constructs an insertion-ordered LinkedHashMap instance with the same mappings as the specified map.

Java example creating a LinkedHashMap

This example shows how LinkedHashMap is created and elements added to it.

Output

As you can see from the output insertion order is maintained. Also null is added only once even if it is added more than once.

LinkedHashMap with access order

Output

Since access order goes from least-recently accessed to most-recently that is why keys 2 and 3 are displayed later because these 2 keys are accessed recently.

Methods in LinkedHashMap class

  • containsValue(Object value)– Returns true if this map maps one or more keys to the specified value.
  • entrySet()– Returns a Set view of the mappings contained in this map.
  • get(Object key)– Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
  • keySet()– Returns a Set view of the keys contained in this map.
  • removeEldestEntry(Map.Entry<K,V> eldest)– Returns true if this map should remove its eldest entry.
  • values()– Returns a Collection view of the values contained in this map.

LinkedHashMap implementation is not synchronized

LinkedHashMap in Java is not thread safe as it is not synchronized. If multiple threads access a linked hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. You can wrap your LinkedHashMap using the Collections.synchronizedMap method.

Java LinkedHashMap iterator

You can’t directly use an iterator with Map. You will have to get the collection view of the Map and then iterate it. The iterators returned by LinkedHashMap’s collection view methods are fail-fast. If the set is modified at any time after the iterator is created, in any way except through the iterator’s own remove method, the Iterator throws a ConcurrentModificationException.

Iterating LinkedHashMap Java example

Output

Performance of LinkedHashMap

Like HashMap, LinkedHashMap provides constant-time performance for the basic operations (add, contains and remove), assuming the hash function disperses elements properly among the buckets. LinkedHashMap’s performance is likely to be just slightly below that of HashMap, due to the added expense of maintaining the linked list. One exception is iteration which is faster in LinkedHashMap because of the linked list traversal.

Reference: https://docs.oracle.com/javase/10/docs/api/java/util/LinkedHashMap.html

That’s all for the topic LinkedHashMap in Java – Map With Order. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.