LinkedHashMap in Java

LinkedHashMap is just like HashMap with an additional feature of maintaining an order of elements inserted into it. HashMap provided the advantage of quick insertion, search, and deletion but it never maintained the track and order of insertion which the LinkedHashMap provides where the elements can be accessed in their insertion order.

LinkedHashMap in Java

Example: The following implementation demonstrates how to create and use a LinkedHashMap.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate working of LinkedHashMap 
import java.util.*; 
    
public class LinkedHashMapExample
    public static void main(String a[]) 
    
        LinkedHashMap<String, String> lhm = 
                       new LinkedHashMap<String, String>(); 
        lhm.put("one", "practice.geeksforgeeks.org"); 
        lhm.put("two", "code.geeksforgeeks.org"); 
        lhm.put("four", "quiz.geeksforgeeks.org"); 
    
        // It prints the elements in same order  
        // as they were inserted     
        System.out.println(lhm); 
    
        System.out.println("Getting value for key 'one': " 
                                       + lhm.get("one")); 
  
        System.out.println("Size of the map: " + lhm.size()); 
  
        System.out.println("Is map empty? " + lhm.isEmpty()); 
  
        System.out.println("Contains key 'two'? "+  
                                  lhm.containsKey("two")); 
  
        System.out.println("Contains value 'practice.geeks"
        +"forgeeks.org'? "+ lhm.containsValue("practice"
        ".geeksforgeeks.org")); 
  
        System.out.println("delete element 'one': " +  
                           lhm.remove("one")); 
  
        System.out.println(lhm); 
    

chevron_right


Output:

{one=practice.geeksforgeeks.org, two=code.geeksforgeeks.org, four=quiz.geeksforgeeks.org}
Getting value for key 'one': practice.geeksforgeeks.org
Size of the map: 3
Is map empty? false
Contains key 'two'? true
Contains value 'practice.geeksforgeeks.org'? true
delete element 'one': practice.geeksforgeeks.org
{two=code.geeksforgeeks.org, four=quiz.geeksforgeeks.org}

Performing various operations on the HashMap class

Let’s see how to perform a few frequently used operations on the LinkedHashMap.



1. Adding Elements: In order to add an element to the LinkedHashMap, we can use the put() method. This is different from HashMap because in HashMap, the insertion order is not retained but it is retained in the LinkedHashMap.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate
// the working of LinkedHashMap
  
import java.util.*;
class GFG {
  
    public static void main(String args[])
    {
        // Default Initialization of a
        // LinkedHashMap
        LinkedHashMap hm1 = new LinkedHashMap();
  
        // Initialization of a LinkedHashMap
        // using Generics
        LinkedHashMap<Integer, String> hm2
            = new LinkedHashMap<Integer, String>();
  
        // Inserting the Elements
        hm1.put(3, "Geeks");
        hm1.put(2, "For");
        hm1.put(1, "Geeks");
  
        hm2.put(new Integer(3), "Geeks");
        hm2.put(new Integer(2), "For");
        hm2.put(new Integer(1), "Geeks");
  
        System.out.println(hm1);
        System.out.println(hm2);
    }
}

chevron_right


Output:

{3=Geeks, 2=For, 1=Geeks}
{3=Geeks, 2=For, 1=Geeks}

2. Changing Elements: After adding the elements if we wish to change the element, it can be done by again adding the element with the put() method. Since the elements in the treemap are indexed using the keys, the value of the key can be changed by simply inserting the updated value for the key for which we wish to change.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate
// the working of LinkedHashMap
  
import java.util.*;
class GFG {
  
    public static void main(String args[])
    {
        // Initialization of a LinkedHashMap
        // using Generics
        LinkedHashMap<Integer, String> hm
            = new LinkedHashMap<Integer, String>();
  
        // Inserting the Elements
        hm.put(3, "Geeks");
        hm.put(2, "Geeks");
        hm.put(1, "Geeks");
  
        System.out.println(hm);
  
        hm.put(2, "For");
  
        System.out.println(hm);
    }
}

chevron_right


Output:

{3=Geeks, 2=Geeks, 1=Geeks}
{3=Geeks, 2=For, 1=Geeks}

3. Removing Element: In order to remove an element from the TreeMap, we can use the remove() method. This method takes the key value and removes the mapping for the key from this treemap if it is present in the map. Apart from that, we can also remove the first entered element from the map if the maximum size is defined as discussed in this article.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate
// the working of LinkedHashMap
  
import java.util.*;
class GFG {
    public static void main(String args[])
    {
        // Initialization of a LinkedHashMap
        // using Generics
        LinkedHashMap<Integer, String> hm
            = new LinkedHashMap<Integer, String>();
  
        // Inserting the Elements
        hm.put(3, "Geeks");
        hm.put(2, "Geeks");
        hm.put(1, "Geeks");
        hm.put(4, "For");
  
        System.out.println(hm);
  
        hm.remove(4);
  
        System.out.println(hm);
    }
}

chevron_right


Output:

{3=Geeks, 2=Geeks, 1=Geeks, 4=For}
{3=Geeks, 2=Geeks, 1=Geeks}

4. Iterating through the LinkedHashMap: There are multiple ways to iterate through the Map. The most famous way is to use a for-each loop and get the keys. The value of the key is found by using the getValue() method.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate
// the working of LinkedHashMap
  
import java.util.*;
class GFG {
    public static void main(String args[])
    {
        // Initialization of a LinkedHashMap
        // using Generics
        LinkedHashMap<Integer, String> hm
            = new LinkedHashMap<Integer, String>();
  
        // Inserting the Elements
        hm.put(3, "Geeks");
        hm.put(2, "For");
        hm.put(1, "Geeks");
  
        for (Map.Entry mapElement : hm.entrySet()) {
            int key
                = (int)mapElement.getKey();
  
            // Finding the value
            String value
                = (String)mapElement.getValue();
  
            System.out.println(key + " : "
                               + value);
        }
    }
}

chevron_right


Output:



3 : Geeks
2 : For
1 : Geeks

Important Features of a LinkedHashMap:

  • A LinkedHashMap contains values based on the key. It implements the Map interface and extends HashMap class.
  • It contains only unique elements.
  • It may have one null key and multiple null values.
  • It is same as HashMap with an additional feature that it maintains insertion order. For example, when we run the code with a HashMap, we get a different order of elements.

How LinkedHashMap work internally?

A LinkedHashMap is an extension of the HashMap class and it implements the Map interface. Therefore, the class is declared as:

public class LinkedHashMap extends HashMap implements Map

In this class, the data is stored in the form of nodes. The implementation of the LinkedHashMap is very similar to a doubly-linked list. Therefore, each node of the LinkedHashMap is represented as:

LinkedHashMap-Node-in-Java

  • Hash: All the input keys are converted into a hash which is a shorter form of the key so that the search and insertion are faster.
  • Key: Since this class extends HashMap, the data is stored in the form of a key-value pair. Therefore, this parameter is the key to the data.
  • Value: For every key, there is a value associated with it. This parameter stores the value of the keys. Due to generics, this value can be of any form.
  • Next: Since the LinkedHashMap stores the insertion order, this contains the address to the next node of the LinkedHashMap.
  • Previous: This parameter contains the address to the previous node of the LinkedHashMap.

Constructors in the LinkedHashMap

To create a LinkedHashMap, we need to create an object of the LinkedHashMap class. The LinkedHashMap class consists of various constructors which allow the possible creation of the array list. The following are the constructors available in this class:

  1. LinkedHashMap(): This is used to construct a default LinkedHashMap constructor.
  2. LinkedHashMap(int capacity): It is used to initialize a particular LinkedHashMap with a specified capacity.
  3. LinkedHashMap(Map map): It is used to initialize a particular LinkedHashMap with the elements of the specified map.
  4. LinkedHashMap(int capacity, float fillRatio): It is used to initialize both the capacity and fill ratio for a LinkedHashMap. A fillRatio also called as loadFactor is a metric that determines when to increase the size of the LinkedHashMap automatically. By default, this value is 0.75 which means that the size of the map is increased when the map is 75% full.
  5. LinkedHashMap(int capacity, float fillRatio, boolean Order): This constructor is also used to initialize both the capacity and fill ratio for a LinkedHashMap along with whether to follow the insertion order or not.
    • True is passed for last access order.
    • False is passed for insertion order.

Methods in Java LinkedHashMap

Method Description
clear() This method is used to remove all the mappings from the map.
containsKey(Object key) This method is used to returns true if a specified element is mapped by one or more keys.
entrySet?() This method returns a Set view of the mappings contained in this map.
forEach?(BiConsumer action) This method performs the BiConsumer operation on each entry of the linkedhashmap until all the entries have been processed or the action throws an exception. The BiConsumer operation is a function operation of the key-value pair of hashtable performed in the order of iteration.
get(Object key) The method is used to retrieve or fetch the value mapped by the specified key.
getOrDefault?(Object key, V defaultValue) This method returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.
keySet?() This method returns a Set view of the keys contained in this map.
removeEldestEntry(Map.Entry eldest) This method in Java is used keep a track of whether the map removes any eldest entry from the map. So each time a new element is added to the LinkedHashMap, the eldest entry is removed from the map.
replaceAll?(BiFunction function) This method replaces each entry’s value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.
values?() This method returns a Collection view of the values contained in this map.

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.




My Personal Notes arrow_drop_up