Table of contents
1.
Introduction
2.
LinkedHashMap Class in Java
2.1.
Syntax of Java LinkedHashMap 
3.
Features of LinkedHashMap 
4.
How LinkedHashMap Work?
5.
Constructors of LinkedHashMap class in Java
6.
Methods of Java LinkedHashMap class
7.
Operations on the LinkedHashMap Class in Java
7.1.
Adding Elements (put() method)
7.2.
Accessing Elements (get() method)
7.3.
Removing Elements (remove() method)
7.4.
Checking the Size (size() method)
7.5.
Checking if a Key Exists (containsKey() method)
7.6.
Checking if a Value Exists (containsValue() method)
7.7.
Iterating Over Elements
7.8.
Clearing All Elements (clear() method)
8.
Example
8.1.
Code 1
8.2.
Code 2
9.
Frequently Asked Questions
9.1.
What is the purpose of LinkedHashMap?
9.2.
Is LinkedHashMap synchronized?
9.3.
How does a LinkedHashMap handle hash collisions?
9.4.
What are the disadvantages of LinkedHashMap in Java?
10.
Conclusion
Last Updated: Oct 7, 2024
Easy

LinkedHashMap in Java

Introduction

HashMap has been part of Java's collection since its version 1.2. This class can be found in Java.util package. It stores the data in the Key-value pair form. 

LinkedHashMap in Java

You can access the data with the help of an index of another type. One object will use the key (index), and another will operate as an integer.

Also read, Duck Number in Java and  Hashcode Method in Java

LinkedHashMap Class in Java

LinkedHashMap is like HashMap with an add-on feature of keeping elements inserted in order. It comes with the advantage of quick insertion, searching, and deletion. It also comes with the benefit of maintaining the insertion order. You can say it's a combination of Hashtable and LinkedList.

Syntax of Java LinkedHashMap 

public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V>
You can also try this code with Online Java Compiler
Run Code

Features of LinkedHashMap 

  • A LinkedHashMap consists of values based on the keys, which can be implemented by extending the HashMap class.
     
  • It consists of unique keys.
     
  • It might contain one null key with multiple null values.
     
  • It comes with an additional feature of maintaining the insertion order.

How LinkedHashMap Work?

  • Maintains Insertion Order: Unlike HashMap, LinkedHashMap maintains the insertion order of elements. This is achieved by using a doubly-linked list that connects entries in the order they are inserted.
     
  • Key-Value Pairs: Similar to HashMap, it stores data in key-value pairs, where each key maps to a specific value, allowing efficient retrieval.
     
  • Access Order Option: LinkedHashMap can also maintain the order based on access if it's configured in the constructor (LinkedHashMap(16, 0.75f, true)), where the recently accessed elements are moved to the end.
     
  • Performance: It offers O(1) time complexity for operations like put(), get(), remove() as it internally uses a hash table.
     
  • Doubly Linked List Structure: Every entry is linked to the next and previous entries, preserving the insertion order or access order based on configuration.
     
  • Removal of Oldest Entry: It can be used to implement a Least Recently Used (LRU) cache by overriding the removeEldestEntry() method, where the oldest entry is removed when the map exceeds a certain size.

Constructors of LinkedHashMap class in Java

The LinkedHashMap class in Java offers five constructors: a default constructor, a constructor with initial capacity, a constructor with capacity and load factor, a constructor that copies elements from another map, and a constructor that defines access order.
 

  • LinkedHashMap(): This is used to create the default LinkedHashMap constructor.
 LinkedHashMap<K,V> llhm = new LinkedHashMap<K,V>();

 

  • LinkedHashMap(int capacity): This hashmap will create LinkedHashMap with user-defined capacity.
 LinkedHashMap<K,V> llhm = new LinkedHashMap<K,V>(int cap);

 

  • LinkedHashMAp(Map<? Extends K,? Extends V> map): It is used to declare a LinkedHashMap with elements of the specified map.
 LinkedHashMap<K, V> llhm = new LinkedHashMap<K, V>(Map<? extends K,​? extends V> map); 

 

  • LinkedHashMap(int cap, float ratio): It is used to create a particular LinkedHashMap with user-defined capacity and ratio. 
 LinkedHashMap<K, V>llhm = new LinkedHashMap<K, V>(int cap, float ratio);

 

  • LinkedHashMap(int capacity, float Ratio, boolean Order): This type will create a constructor that initializes both capacity and ratio. Here the order is the access order for insertion.
 LinkedHashMap<K, V> llhm = new LinkedHashMap<K, V>(int capacity, float fillRatio, boolean Order);

Methods of Java LinkedHashMap class

  • V get(Object key): This function will return the specified key's value.
     
  • Void clear(): It helps to remove all the key-value pairs from the map.
     
  • boolean containsValue(Object value): It returns true if the map maps one or more keys to the specific matter. 
     
  • Set<Map.Entry<K, V>> entrySet(): This function will return the set view of the mappings which are contained in the map.
     
  • Set<K>keySet(): This will return a set idea of the keys contained in the set.

Operations on the LinkedHashMap Class in Java

The LinkedHashMap class supports several common operations such as adding, removing, retrieving, and iterating over elements. Below are the key operations explained with code examples and their output.

Adding Elements (put() method)

The put() method is used to insert key-value pairs into a LinkedHashMap.

import java.util.LinkedHashMap;
public class LinkedHashMapExample {
   public static void main(String[] args) {
       LinkedHashMap<Integer, String> map = new LinkedHashMap<>();
       
       // Adding key-value pairs
       map.put(1, "Apple");
       map.put(2, "Banana");
       map.put(3, "Orange");
       System.out.println("LinkedHashMap after insertion: " + map);
   }
}
You can also try this code with Online Java Compiler
Run Code


Output

LinkedHashMap after insertion: {1=Apple, 2=Banana, 3=Orange}
You can also try this code with Online Java Compiler
Run Code

Accessing Elements (get() method)

The get() method retrieves the value associated with a specific key.

import java.util.LinkedHashMap;
public class LinkedHashMapExample {
   public static void main(String[] args) {
       LinkedHashMap<Integer, String> map = new LinkedHashMap<>();
       
       map.put(1, "Apple");
       map.put(2, "Banana");
       
       // Accessing a value using the key
       String fruit = map.get(1);
       System.out.println("Value for key 1: " + fruit);
   }
}

You can also try this code with Online Java Compiler
Run Code


Output

Value for key 1: Apple

Removing Elements (remove() method)

The remove() method removes the key-value pair associated with the specified key.

import java.util.LinkedHashMap;
public class LinkedHashMapExample {
   public static void main(String[] args) {
       LinkedHashMap<Integer, String> map = new LinkedHashMap<>();
       
       map.put(1, "Apple");
       map.put(2, "Banana");
       map.put(3, "Orange");
       
       // Removing a key-value pair
       map.remove(2);
       System.out.println("LinkedHashMap after removal: " + map);
   }
}
You can also try this code with Online Java Compiler
Run Code


Output

LinkedHashMap after removal: {1=Apple, 3=Orange}

Checking the Size (size() method)

The size() method returns the number of key-value pairs in the map.

import java.util.LinkedHashMap;

public class LinkedHashMapExample {
    public static void main(String[] args) {
        LinkedHashMap<Integer, String> map = new LinkedHashMap<>();
        
        map.put(1, "Apple");
        map.put(2, "Banana");
        
        // Getting the size of the LinkedHashMap
        System.out.println("Size of LinkedHashMap: " + map.size());
    }
}
You can also try this code with Online Java Compiler
Run Code


Output

Size of LinkedHashMap: 2

Checking if a Key Exists (containsKey() method)

The containsKey() method checks if a specific key is present in the map.

import java.util.LinkedHashMap;

public class LinkedHashMapExample {
    public static void main(String[] args) {
        LinkedHashMap<Integer, String> map = new LinkedHashMap<>();
        
        map.put(1, "Apple");
        map.put(2, "Banana");

        // Checking if key 1 exists
        if (map.containsKey(1)) {
            System.out.println("Key 1 exists in the LinkedHashMap.");
        }
    }
}
You can also try this code with Online Java Compiler
Run Code


Output

Key 1 exists in the LinkedHashMap.

Checking if a Value Exists (containsValue() method)

The containsValue() method checks if a specific value is present in the map.

import java.util.LinkedHashMap;

public class LinkedHashMapExample {
    public static void main(String[] args) {
        LinkedHashMap<Integer, String> map = new LinkedHashMap<>();
        
        map.put(1, "Apple");
        map.put(2, "Banana");

        // Checking if value "Banana" exists
        if (map.containsValue("Banana")) {
            System.out.println("Value 'Banana' exists in the LinkedHashMap.");
        }
    }
}
You can also try this code with Online Java Compiler
Run Code


Output

Value 'Banana' exists in the LinkedHashMap.
You can also try this code with Online Java Compiler
Run Code

Iterating Over Elements

You can iterate over the keys and values in the LinkedHashMap using a for loop or an Iterator.

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

public class LinkedHashMapExample {
    public static void main(String[] args) {
        LinkedHashMap<Integer, String> map = new LinkedHashMap<>();
        
        map.put(1, "Apple");
        map.put(2, "Banana");
        map.put(3, "Orange");

        // Iterating over key-value pairs
        for (Map.Entry<Integer, String> entry : map.entrySet()) {
            System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
        }
    }
}
You can also try this code with Online Java Compiler
Run Code


Output

Key: 1, Value: Apple
Key: 2, Value: Banana
Key: 3, Value: Orange

Clearing All Elements (clear() method)

The clear() method removes all key-value pairs from the LinkedHashMap.

import java.util.LinkedHashMap;

public class LinkedHashMapExample {
    public static void main(String[] args) {
        LinkedHashMap<Integer, String> map = new LinkedHashMap<>();
        
        map.put(1, "Apple");
        map.put(2, "Banana");
        
        // Clearing the LinkedHashMap
        map.clear();
        System.out.println("LinkedHashMap after clearing: " + map);
    }
}
You can also try this code with Online Java Compiler
Run Code


Output

LinkedHashMap after clearing: {}

Example

Code 1

import java.util.*;  
public class Ex1{  
     public static void main(String args[]){  
           
        LinkedHashMap<Integer,String> hm=new LinkedHashMap<Integer,String>();  
          
        hm.put(100,"Mohammad");  
        hm.put(101,"Saalim");  
        hm.put(102,"Mohtashim");  
          
        for(Map.Entry m:hm.entrySet()){  
            System.out.println(m.getKey()+" "+m.getValue());  
        }  
    }  
}  
You can also try this code with Online Java Compiler
Run Code

Output

100 Mohammad
101 Saalim
102 Mohtashim
You can also try this code with Online Java Compiler
Run Code


Try it on java online compiler.
In this example, we have used a LinkedHashMap, and we used certain functions which are put. This function helps us to put the value in the HashMap. After placing the value, we print the values entered in the map.

Code 2

import java.util.*;  
public class Ex2 {  
    public static void main(String args[]) {  
        Map<Integer,String> map=new LinkedHashMap<Integer,String>();        
       
        map.put(101,"Saalim");    
        map.put(102,"CN");    
        map.put(103,"Maaz");
         
        System.out.println("Before invoking remove() method: "+map);   
    
        map.remove(102);
        System.out.println("After invoking remove() method: "+map);
    }      
}   
You can also try this code with Online Java Compiler
Run Code

Output

Before invoking remove() method: {101=Saalim, 102=CN, 103=Maaz}
After invoking remove() method: {101=Saalim, 103=Maaz}
You can also try this code with Online Java Compiler
Run Code


In this code, we have added specific names and some numbers. We have used the put function to add the names and their values. After putting the names, we used a function remove to remove the specific entry. 

Also see,  Swap Function in Java

Frequently Asked Questions

What is the purpose of LinkedHashMap?

LinkedHashMap is a Hash table and an implementation of LinkedList of the Map interface, along with the predictable iteration order. 

Is LinkedHashMap synchronized?

It's not synchronized, just like HashMap, so if you are going to access it from different threads, at least one of these threads is likely to change.

How does a LinkedHashMap handle hash collisions?

In a LinkedHashMap, hash collisions are handled by storing multiple entries in a bucket (linked list), similar to HashMap. When two keys have the same hash code, they are placed in the same bucket and linked sequentially within that bucket.

What are the disadvantages of LinkedHashMap in Java?

The primary disadvantages of LinkedHashMap are its higher memory usage due to maintaining a doubly-linked list for insertion order and slightly slower performance compared to HashMap, especially in large datasets, because of the overhead of managing the linked structure.

Conclusion

In this article, we thoroughly discussed the LinkedHashMap in Java. We began by exploring its constructors and the underlying structure that maintains insertion order. We then examined its operations, handling of hash collisions, and its use cases. Finally, we highlighted the advantages and disadvantages, providing a comprehensive understanding of when and how to use LinkedHashMap effectively.

Recommended Readings:

If you want to learn more about this concept and practice more problems, please visit our website, Problems on HashMap.

Live masterclass