LinkedHashMap in Java | Code, Examples, Advantages (Complete Guide)

LinkedHashMap in Java | Code, Examples, Advantages (Complete Guide)

What is LinkedHashMap in Java?

LinkedHashMap is a class in the Java Collections Framework that extends the HashMap class. It is a data structure that stores key-value pairs just like HashMap, but it maintains the order in which the entries were inserted.

In other words, we can say that it is a combination of a HashMap and a doubly-linked list with faster iteration over the entries in the order they were added.

Create a LinkedHashMap in Java

Let’s understand how to create a LinkedHashMap in Java with the running code.

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

class MainClass {
	public static void main(String[] args) {

		// Creating a LinkedHashMap
		Map<String, Integer> map = new LinkedHashMap<>();

        // Adding some key-value pairs to the map
        map.put("Rohan", 90);
        map.put("Mohan", 80);
        map.put("Sohan", 70);
        map.put("David", 60);

        // Iterating over the entries in the order they were added
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }

	}
}

Output:

Rohan: 90
Mohan: 80
Sohan: 70
David: 60

As you can see, the entries are printed in the order in which they were added to the LinkedHashMap.

Removing and Traversing elements

Here, we are removing elements from the LinkedHashMap and traversing the rest of the elements.

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

class MainClass {
	public static void main(String[] args) {

		// Creating a LinkedHashMap
		Map<String, Integer> map = new LinkedHashMap<>();

        // Adding some key-value pairs to the map
        map.put("Rohan", 90);
        map.put("Mohan", 80);
        map.put("Sohan", 70);
        map.put("David", 60);

        
        System.out.println(map);
        
        // Removing elements
        map.remove("Mohan");
        
        System.out.println("Map after removing one element: ");
        // Traversing elements
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }

	}
}

Output:

{Rohan=90, Mohan=80, Sohan=70, David=60}
Map after removing one element: 
Rohan: 90
Sohan: 70
David: 60

Java LinkedHashMap Methods

LinkedHashMap provides all the methods available in HashMap, and it also provides additional methods for manipulating the order of the entries in the map.

Here are some of the additional methods:

  • getFirst():
    It returns the first entry in the map.
  • getLast():
    It returns the last entry in the map.
  • removeEldestEntry(Map.Entry<K,V> eldest):
    This method can be overridden to impose a policy for removing the oldest entry in the map when a new entry is added.

Overall, LinkedHashMap is a useful data structure when you need to maintain the order of entries in a map, while still allowing fast access to individual entries.

LinkedHashMap Coding Examples

Let’s see some more examples of LinkedHashMap.

Iterating over the entries in reverse order

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.Map;
import java.util.Map.Entry;

class MainClass {
	public static void main(String[] args) {

		// Creating a LinkedHashMap
		Map<String, Integer> map = new LinkedHashMap<>();

        // Adding some key-value pairs to the map
        map.put("Rohan", 90);
        map.put("Mohan", 80);
        map.put("Sohan", 70);
        map.put("David", 60);


        ListIterator<Entry<String, Integer>> iter = new LinkedList<>(new ArrayList<>(map.entrySet())).listIterator(map.size());
        while (iter.hasPrevious()) {
            Entry<String, Integer> entry = iter.previous();
            String key = entry.getKey();
            int value = entry.getValue();
            System.out.println(key + " = " + value);
        }

	}
}

Output:

David = 60
Sohan = 70
Mohan = 80
Rohan = 90

Example for removing the oldest entry

In this example, we create a LinkedHashMap with an initial capacity of 4 and a load factor of 0.75. We also override the removeEldestEntry method to remove the oldest entry when the map contains more than 3 entries.

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

class MainClass {
	public static void main(String[] args) {

		// Creating a LinkedHashMap
		Map<String, Integer> map = new LinkedHashMap<String, Integer>(4, 0.75f, true) {
            protected boolean removeEldestEntry(Map.Entry<String, Integer> eldest) {
                return size() > 3;
            }
        };

        // Adding some key-value pairs to the map
        map.put("Rohan", 90);
        map.put("Mohan", 80);
        map.put("Sohan", 70);
        
        System.out.println(map);

        // Adding new entry
        map.put("John", 45);
        
        System.out.println(map);
	}
}

Output:

{Rohan=90, Mohan=80, Sohan=70}
{Mohan=80, Sohan=70, John=45}

When we add a new entry to the map, the oldest entry is removed and the remaining entries are shifted to make room for the new entry. 

When we iterate over the entries in the map, we can see that the oldest entry (“Rohan”) has been removed and the remaining entries are printed in the order in which they were added.

Advantages of LinkedHashMap in Java

Here are some advantages of using LinkedHashMap in Java.

Maintains insertion order:

LinkedHashMap maintains the order in which the entries were inserted into the map. This means that when you iterate over the entries in the map, they are returned in the order in which they were added. This can be useful if you need to maintain a specific order of elements.

Supports access order:

LinkedHashMap can also maintain the order of the entries based on their access pattern. When you access an entry in the map (e.g., by calling get()), it is moved to the end of the linked list. This allows you to iterate over the entries in the order in which they were last accessed.

Faster iteration:

LinkedHashMap allows for faster iteration over the entries in the order they were added. This is because the entries are stored in a doubly-linked list, which allows for constant-time insertion and deletion.

Inherits from HashMap:

LinkedHashMap inherits all the methods and functionality of HashMap, which is a widely used and well-tested data structure. This means that you can use LinkedHashMap as a drop-in replacement for HashMap in most cases.

Conclusion

LinkedHashMap is a data structure in Java that combines the features of a hash table and a linked list. It maintains the order of the entries in the map, which can be useful in a variety of contexts. It also supports access order, which allows for faster iteration and can be used as a cache.

Leave a Reply

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