June 29, 2022

Java LinkedHashMap With Examples

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.

import java.util.LinkedHashMap;
import java.util.Map;

public class LinkedHMDemo {
  public static void main(String[] args) {
    // Creating LinkedHashMap
    Map<String, String> carMap = new LinkedHashMap<String, String>();
    // Storing elements
    carMap.put("1", "Audi");
    carMap.put("2", "BMW");
    carMap.put(null, "Mercedes");
    carMap.put("3", "Jaguar");
    carMap.put("4", "Mini Cooper");
    carMap.put(null, "Range Rover");

    for(Map.Entry<String, String> entry : carMap.entrySet()){
      System.out.println("Key is " + entry.getKey() + " Value is " + entry.getValue());
    }
  }
}
Output
Key is 1 Value is Audi
Key is 2 Value is BMW
Key is null Value is Range Rover
Key is 3 Value is Jaguar
Key is 4 Value is Mini Cooper

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

import java.util.LinkedHashMap;
import java.util.Map;

public class LinkedHMDemo {
  public static void main(String[] args) {
    // Creating LinkedHashMap
    Map<String, String> carMap = new LinkedHashMap<String, String>(16, 0.75f, true);
    // Storing elements
    carMap.put("1", "Audi");
    carMap.put("2", "BMW");
    carMap.put("3", "Jaguar");
    carMap.put("4", "Mini Cooper");
    System.out.println("value- " + carMap.get("2"));
    System.out.println("value- " + carMap.get("3"));
    for(Map.Entry<String, String> entry : carMap.entrySet()){
      System.out.println("Key is " + entry.getKey() + " Value is " + entry.getValue());
    }
  }
}
Output
Key is 1 Value is Audi
Key is 4 Value is Mini Cooper
Key is 2 Value is BMW
Key is 3 Value is Jaguar

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 LinkedHashMap 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.

Map m = Collections.synchronizedMap(new LinkedHashMap(...));

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
public class LinkedHMDemo {
  public static void main(String[] args) {
    // Creating HashMap
    Map<String, String> carMap = new LinkedHashMap<String, String>();
    // Storing elements
    carMap.put("1", "Audi");
    carMap.put("2", "BMW");
    carMap.put("3", "Jaguar");
    carMap.put("4", "Mini Cooper");
    // iterating map
    Iterator<Map.Entry<String, String>> itr = carMap.entrySet().iterator();
    while(itr.hasNext()) {
      Map.Entry<String, String> entry = itr.next();
      System.out.println("Key is " + entry.getKey() + " Value is " + entry.getValue());
    }
  }
}
Output
Key is 1 Value is Audi
Key is 2 Value is BMW
Key is 3 Value is Jaguar
Key is 4 Value is Mini Cooper

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/en/java/javase/12/docs/api/java.base/java/util/LinkedHashMap.html

That's all for the topic Java LinkedHashMap With Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment