dsa

Java LinkedHashMap

In this tutorial, we will learn about the Java LinkedHashMap class and its operations with the help of examples.

The LinkedHashMap class of the Java collections framework provides the hash table and linked list implementation of the Map interface.

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. Let’s see how to create a map object using this class.

linkedhashmap

Example:

// Java Program to illustrate the LinkedHashmap Class 
import java.util.*; 

public class Codemistic { 

	public static void main(String[] args) 
	{ 
		Map<String, Integer> map 
			= new LinkedHashMap<>(); 

		map.put("ayush", 10); 
		map.put("anvi", 30); 
		map.put("pragya", 20); 

		for (Map.Entry<String, Integer> e : map.entrySet()) 
			System.out.println(e.getKey() + " "
							+ e.getValue()); 
	} 
} 
output:
ayush 20
anvi 10
pragya 30

Important Features of a LinkedHashMap:

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<k, v=""> 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<k, v=""> 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.