LinkedHashMap in Java | Methods, Example

LinkedHashMap in Java is a concrete class that is HashTable and LinkedList implementation of Map interface. It stores entries using a doubly-linked list. This class extends the HashMap class with a linked-list implementation that supports an ordering of the entries in the map.

LinkedHashMap in Java was added in JDK 1.4 version. It is exactly the same as HashMap (including constructors and methods) except for the following differences:

1. The underlying data structure of HashMap is HashTable whereas, the underlying data structure of LinkedHashMap is HashTable and LinkedList (Hybrid data structure).

2. Insertion order is not preserved in the HashMap because it is based on the hashCode of Key. But in the case of LinkedHashMap, the insertion order of elements is preserved because it is based on the Key insertion order, that is, the order in which keys are inserted in the map.

3. HashMap was introduced in Java 1.2 version whereas, LinkedHashMap was introduced in Java 1.4 version.

Hierarchy of LinkedHashMap in Java


LinkedHashMap implementation in Java is a subclass of HashMap class. That is, LinkedHashMap class extends the HashMap class and implements Map interface.

The hierarchy diagram of LinkedHashMap is shown in the below figure.

Hierarchy diagram of LinkedHashMap in Java

LinkedHashMap class declaration


LinkedHashMap is a generic class that is present in java.util.LinkedHashMap package. It has the following declaration.

public class LinkedHashMap<K,V>
  extends HashMap<K,V>
  implements Map<K,V>

Here, K defines the type of keys, and V defines the type of values.

Features of LinkedHashMap in Java


There are several features of LinkedHashMap in Java that should keep in mind. They are as follows:

1. The underlying data structure of LinkedHashMap is HashTable and LinkedList.

2. Java LinkedHashMap maintains the insertion order. The entries in Java LinkedHashMap can be retrieved either in the order in which they were inserted into the map (known as insertion order) or in the order in which they were last accessed, from least to most recently accessed.


3. LinkedHashMap contains unique elements. It contains values based on keys.

4. LinkedHashMap allows only one null key but can have multiple null values.

5. LinkedHashMap in Java is non synchronized. That is, multiple threads can access the same LinkedHashMap object simultaneously.

6. The default initial capacity of LinkedHashMap class is 16 with a load factor of 0.75.

Constructors of Java LinkedHashMap class


Java LinkedHashMap class has the following constructors. They are as follows:

1. LinkedHashMap(): This constructor is used to create a default LinkedHashMap object. It constructs an empty insertion-ordered LinkedHashMap object with the default initial capacity 16 and load factor 0.75.

The general syntax to construct default LinkedHashMap object is as follows:

LinkedHashMap lhmap = new LinkedHashMap();
or,
LinkedHashMap<K,V> lhmap = new LinkedHashMap<>(); // Generic form

2. LinkedHashMap(int initialCapacity): It is used to create an empty insertion-ordered LinkedHashMap object with the specified initial capacity and a default load factor of 0.75. The general syntax in generic form is as follows:

LinkedHashMap<K,V> lhmap = new LinkedHashMap<>(int initialCapacity);

3. LinkedHashMap(int initialCapacity, float loadFactor): It is used to create an empty insertion-ordered LinkedHashMap object with the specified initial capacity and load factor. The general syntax in generic form is given below:

LinkedHashMap<K,V> lhmap = new LinkedHashMap<>(int initialCapacity, float loadFactor);
For example:
LinkedHashMap<String, Integer> lhmap = new LinkedHashMap<>(16, 0.75f);

4. LinkedHashMap(Map m): This constructor is used to create an insertion-ordered LinkedHashMap object with the elements from the given Map m.

5. LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder): This constructor is used to create an empty LinkedHashMap instance with the specified initial capacity, load factor, and ordering mode.

If accessOrder is true, access-order is used. If it is false, the insertion order is used. The general syntax to create LinkedHashMap object with three arguments of constructor is as follows:

LinkedHashMap<K,V> lhmap = new LinkedHashMap<int initialCapacity, float loadFactor, boolean accessOrder>();

For example:
LinkedHashMap<String, String> lhmap = new LinkedHashMap<>(16, 0.75f, true); // For access order.
LinkedHashMap<String, String> lhmap = new LinkedHashMap<>(16, 0.75f, false); //  For insertion order

Note:

The first four constructors of linked hash map are analogous to the four constructors of hash map class. In each case, the created linked hash map maintains the insertion order.


The last constructor of linked hash map allows us to specify whether elements will be stored in the linked list by insertion order, or by order of last access.

LinkedHashMap Methods in Java


The methods of LinkedHashMap are exactly the same as HashMap class methods, except for one method that is added by LinkedHashMap. This method is removeEldestEntry().

The general syntax for this method is as follows:

protected boolean removeEldestEntry(Map.Entry<K,V> e)

The parameter e is the least recently added entry in the map, or if it is an access-ordered map, the least recently accessed entry.

This method returns true if the map removes this eldest (oldest) entry. If this entry is retained, or not removed, this method returns false.

The removeEldestEntry() method is called by put() and putAll() after adding a new entry into the map. It helps to remove the eldest entry each time when a new entry is added.

This method is useful if the map represents a cache. It allows the map to reduce memory consumption by deleting stale entries.

Java LinkedHashMap Example Programs


Let’s take some example programs where we will perform frequently asked operations based on the methods of LinkedHashMap.

1. Adding and checking size operations:

Let’s write a Java program where we will perform various operations such as adding elements, checking the size of linked hash map, and linked hash map is empty or not before adding elements into it. Look at the program source code.

Program code 1:

import java.util.LinkedHashMap;
public class LinkedHashMapEx1 {
public static void main(String[] args) 
{	
// Create a LinkedHashMap instance.	
   LinkedHashMap<String, Integer> lhmap = new LinkedHashMap<>();

// Checking the size of linked hash map before adding entries.
   int size = lhmap.size();
   System.out.println("Size of LinkedHashMap before adding entries: " +size);

// Checking linked hash map is empty or not before adding entries. 
   boolean isEmpty = lhmap.isEmpty();
   System.out.println("Is LinkedHashMap empty: " +isEmpty);
 
// Adding entries in linked hash map. 
   lhmap.put("John", 30);
   lhmap.put("Peter", 25);
   lhmap.put("Ricky", 23);
   lhmap.put("Deep", 28);
   lhmap.put("Mark", 32);
    
   System.out.println("Display entries in LinkedHashMap");
   System.out.println(lhmap);

   int size2 = lhmap.size();
   System.out.println("Size of LinkedHashMap after adding entries: " +size2);

// Adding null as key and value.
   lhmap.put(null, null);
   System.out.println(lhmap);
 }
Output:
      Size of LinkedHashMap before adding entries: 0
      Is LinkedHashMap empty: true
      Display entries in LinkedHashMap
      {John=30, Peter=25, Ricky=23, Deep=28, Mark=32}
      Size of LinkedHashMap after adding entries: 5
      {John=30, Peter=25, Ricky=23, Deep=28, Mark=32, null=null}

2. Let’s take a program where we will create LinkedHashMap instance with the third argument of constructor set to true. The mappings En=English, Hi=Hindi, Ta=Tamil, De=German, Fr=French will be inserted into this object and entries will be displayed on the console. Look at the program source code to understand better.

Program code 2:

import java.util.LinkedHashMap;
public class LinkedHashMapEx2 {
public static void main(String[] args) 
{
  LinkedHashMap<String, String> lhmap = new LinkedHashMap<>(16, 0.75f, true); 
  lhmap.put("En", "English");
  lhmap.put("Hi", "Hindi");
  lhmap.put("Ta", "Tamil");
  lhmap.put("De", "German");
  lhmap.put("Fr", "French");
    
  System.out.println("Initially, entries in LinkedHashMap lhmap: " +lhmap);
  System.out.println("Value corresponding to key Hi: " +lhmap.get("Hi"));

  System.out.println("Value corresponding to key En: " +lhmap.get("En"));
  System.out.println("After accessing entries Hi and En: " +lhmap);

  System.out.println("\n");

  LinkedHashMap<String, String> lhmap2 = new LinkedHashMap<>(16, 0.75f, false); 
   lhmap2.put("En", "English");
   lhmap2.put("Hi", "Hindi");
   lhmap2.put("Ta", "Tamil");
   lhmap2.put("De", "German");
   lhmap2.put("Fr", "French");

  System.out.println("Initially, entries in LinkedHashMap lhmap2: " +lhmap2);
  System.out.println("Value corresponding to key Hi: " +lhmap.get("Hi"));
 
  System.out.println("Value corresponding to key En: " +lhmap.get("En"));
  System.out.println("After accessing entries Hi and En: " +lhmap2);
 }
}
Output:
     Initially, entries in LinkedHashMap lhmap: {En=English, Hi=Hindi, Ta=Tamil, De=German, Fr=French}
     Value corresponding to key Hi: Hindi
     Value corresponding to key En: English
     After accessing entries Hi and En: {Ta=Tamil, De=German, Fr=French, Hi=Hindi, En=English}

     Initially, entries in LinkedHashMap lhmap2: {En=English, Hi=Hindi, Ta=Tamil, De=German, Fr=French}
     Value corresponding to key Hi: Hindi
     Value corresponding to key En: English
     After accessing entries Hi and En: {En=English, Hi=Hindi, Ta=Tamil, De=German, Fr=French}

As you can see in the above program, the mapping Hi=Hindi is accessed, followed by the mapping En=English. After accessing entries, the mappings are displayed in the order that they were last accessed.

Another LinkedHashMap instance is created with the third argument set to false. The same steps are followed here as followed by previous steps. After accessing entries, the insertion order is maintained.


3. Remove and replace operations:

Let’s take an example program where we will perform remove, and replace operations. We will also check that a particular value or key is present in linked hash map or not. Look at the following source code.

Program code 3:

import java.util.LinkedHashMap;
public class LinkedHashMapEx3 {
public static void main(String[] args) 
{	
  LinkedHashMap<String, String> lhmap = new LinkedHashMap<>(); 
  lhmap.put("En", "English");
  lhmap.put("Hi", "Hindi");
  lhmap.put("Ta", "Tamil");
  lhmap.put("De", "German");
  lhmap.put("Fr", "French");
    
  System.out.println("Entries in LinkedHashMap lhmap: " +lhmap);

// Call remove() method to delete an entry for specified key.
   lhmap.remove("De");
   System.out.println("Updated Entries in LinkedHashMap: " +lhmap);
   
// Call replace() method to replace specified value for a specified key.
   lhmap.replace("En", "English-US");
   System.out.println("After replacing, updated entries in LinkedHashMap: " +lhmap);

// Call containsValue() method to determine specified value for specified key.
   boolean value = lhmap.containsValue("Hindi");
   System.out.println("Is Hindi present in LinkedHashMap: " +value);
 }
}
Output:
     Entries in LinkedHashMap lhmap: {En=English, Hi=Hindi, Ta=Tamil, De=German, Fr=French}
     Updated Entries in LinkedHashMap: {En=English, Hi=Hindi, Ta=Tamil, Fr=French}
     After replacing, updated entries in LinkedHashMap: {Hi=Hindi, Ta=Tamil, Fr=French, En=English-US}
     Is Hindi present in LinkedHashMap: true

How to Iterate LinkedHashMap in Java?


Let’s take an example program where we will iterate entries, keys, and values of LinkedHashMap using Java iterator concept. Look at the source code.

Program code 4:

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
public class IteratingLinkedHashMap {
	
public static void main(String[] args) 
{	
  LinkedHashMap<Character, String> lhmap = new LinkedHashMap<>(); 
  lhmap.put('R', "Red");
  lhmap.put('G', "Green");
  lhmap.put('B', "Brown");
  lhmap.put('O', "Orange");
  lhmap.put('P', "Pink");
    
  System.out.println("Entries in LinkedHashMap lhmap: " +lhmap);

  Iterator<Entry<Character, String>> itr = lhmap.entrySet().iterator(); // entrySet is a method that is used to get view of entries of a linked hash map. 
  System.out.println("Iterating Entries of LinkedHashMap");
  while(itr.hasNext())  
  {  
    Object key = itr.next();  
    System.out.println(key);  
  }
  System.out.println("\n");

  Iterator<Character> itr2 = lhmap.keySet().iterator(); // keySet is a method that is used to get view of keys of a linked hash map.
  System.out.println("Iterating Keys of LinkedHashMap");
  while(itr2.hasNext())
  {
    Object keyView = itr2.next();
    System.out.println(keyView);
  }
  System.out.println("\n");

  Iterator<String> itr3 = lhmap.values().iterator(); // values is a method that is used to get values of keys of a linked hash map.
  System.out.println("Iterating Values of LinkedHashMap");
  while(itr3.hasNext())
  {
    Object valuesView = itr3.next();
    System.out.println(valuesView);
  } 
 }
}
Output:
      Entries in LinkedHashMap lhmap: {R=Red, G=Green, B=Brown, O=Orange, P=Pink}
      Iterating Entries of LinkedHashMap
      R=Red
      G=Green
      B=Brown
      O=Orange
      P=Pink

      Iterating Keys of LinkedHashMap
      R
      G
      B
      O
      P

      Iterating Values of LinkedHashMap
      Red
      Green
      Brown
      Orange
      Pink

Let’s take an example in which we will iterate entries of linked hashmap using forEach() method.

Program code 5:

import java.util.LinkedHashMap;
public class IteratingLinkedHashMap2 {
public static void main(String[] args) 
{	
  LinkedHashMap<Character, String> lhmap = new LinkedHashMap<>(); 
  lhmap.put('R', "Red");
  lhmap.put('G', "Green");
  lhmap.put('B', "Brown");
  lhmap.put('O', "Orange");
  lhmap.put('P', "Pink");

  System.out.println("Iterating Entries of LinkedHashMap");

// Iteration over map using forEach() method.   
   lhmap.forEach((k,v) -> System.out.println("Color code: "+ k + ", Color name: " + v)); 
 }
}
Output:
      Iterating Entries of LinkedHashMap
      Color code: R, Color name: Red
      Color code: G, Color name: Green
      Color code: B, Color name: Brown
      Color code: O, Color name: Orange
      Color code: P, Color name: Pink

Program based on removeEldestEntry() method


Let’s take an example program in which we will perform an operation based on removeEldestEntry() method.

Program code 6:

import java.util.LinkedHashMap;
import java.util.Map;
public class LinkedHashMapEx1 {
public static void main(String[] args) 
{
  final int max = 5;	
  LinkedHashMap<String, String> lhmap = new LinkedHashMap<String,String>() { 
  protected boolean removeEldestEntry(Map.Entry<String, String> e)
  { 
    return size() > max; 
  } 
 }; 
  
  lhmap.put("R", "Red");
  lhmap.put("G", "Green");
  lhmap.put("B", "Brown");
  lhmap.put("O", "Orange");
  lhmap.put("P", "Pink");

  System.out.println("Initial Entries of LinkedHashMap");
  System.out.println(lhmap);

// Adding more entry into linked hash map.
   lhmap.put("W", "White");
   System.out.println("Displaying Map after adding more entry: " +lhmap);

   lhmap.put("Y", "Yellow"); // Adding one more entry into linked hash map.
   System.out.println("Displaying Map after adding one more entry: " +lhmap);
 }
}
Output:
       Initial Entries of LinkedHashMap
       {R=Red, G=Green, B=Brown, O=Orange, P=Pink}
       Displaying Map after adding more entry: {G=Green, B=Brown, O=Orange, P=Pink, W=White}
       Displaying Map after adding one more entry: {B=Brown, O=Orange, P=Pink, W=White, Y=Yellow}

When to Use LinkedHashMap in Java?


LinkedHashMap can be used when you want to preserve the insertion order. Java LinkedHashMap is slower than HashMap but it is suitable when more number of insertions and deletions happen.

Which implementation is better to use: HashMap or LinkedHashMap?


Both HashMap and LinkedHashMap classes provide comparable performance but HashMap is a natural choice if the ordering of elements is not an issue.

Adding, removing, and finding entries in a LinkedHashMap is slightly slower than in HashMap because it needs to maintain the order of doubly linked list in addition to the hashed data structure.

Advantages of using a LinkedHashMap in Java


There are several advantages of using a LinkedHashMap in Java. They are as:

  • LinkedHashMap maintains the insertion order of elements, which is useful in scenarios where the order of elements is essential.
  • It provides efficient access to the most recently accessed elements, which makes it a good choice for cases where elements are frequently accessed.
  • LinkedHashMap provides the almost same performance as a HashMap for most operations, except it maintains the order of elements.

Disadvantages of using LinkedHashMap in Java


There are also some disadvantages of using a LinkedHashMap in Java. They are:

  • LinkedHashMap has a slightly higher memory footprint than a HashMap, because of additional overhead of maintaining the order of elements.
  • It provides a slightly slower performance than a HashMap for some operations, due to the additional overhead of maintaining the order of elements.

In this tutorial.we have discussed LinkedHashMap in Java with example programs. Hope that you will have understood all the basic points of linked hash map and practiced all the above example programs.

In the next tutoria, we will understand another important topic TreeMap in Java with the help of some important example coding.
Thanks for reading!!!

⇐ PrevNext ⇒

Please share your love