LinkedHashMap in Java with Example.

LinkedHashMap Class in java:

LinkedHashMap class is Hash table and linked list implementation of the Map interface, with predictable iteration order.

LinkedHashMap extends the HashMap class which is another very commonly used implementation of the Map interface –

As we know that HashMap class doesn’t guarantee to specific order . HashMap produces the elements in a random order every time you iterate over it.

If you want a predictable iteration order of the elements in a Map, then you can use a LinkedHashMap.

The iteration order in a LinkedHashMap is normally the order in which the elements are inserted. However, it also provides a special constructor using which you can change the iteration order from the least-recently accessed element to the most-recently accessed element and vice versa. This kind of iteration order can be useful in building LRU caches. In any case, the iteration order is predictable.

Important point about LinkedHashMap:

LinkedHashMap does not contains duplicates keys.

LinkedHashMap contains one null as key and any number of null as values.

In LinkedHashMap iteration order of elements is predictable.

similar to HashMap, LinkedHashMap is not thread-safe. You must explicitly synchronize concurrent access to a LinkedHashMap in a multi-threaded environment.

Constructor and Description
LinkedHashMap()Constructs an empty insertion-ordered LinkedHashMap instance with the default initial capacity (16) and load factor (0.75).
LinkedHashMap(int initialCapacity)Constructs an empty insertion-ordered LinkedHashMap instance with the specified initial capacity and a default load factor (0.75).
LinkedHashMap(int initialCapacity, float loadFactor)Constructs an empty insertion-ordered LinkedHashMap instance with the specified initial capacity and load factor.
LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder)Constructs an empty LinkedHashMap instance with the specified initial capacity, load factor and ordering mode.
LinkedHashMap(Map<? extends K,? extends V> m)Constructs an insertion-ordered LinkedHashMap instance with the same mappings as the specified map.

Creating and Initializing a LinkedHashMap

The following example shows how to create a LinkedHashMap and add new key-value pairs to it.

import java.util.LinkedHashMap;
 public class CreateLinkedHashMapDemo {
     public static void main(String[] args) {
         // Creating a LinkedHashMap
         LinkedHashMap linkedHashMap = new LinkedHashMap<>();
     // Adding new key-value pairs to the LinkedHashMap
     linkedHashMap.put("one", 1);
     linkedHashMap.put("two", 2);
     linkedHashMap.put("three",3);
     linkedHashMap.put("four", 4);
     // Add a new key-value pair only if the key does not exist in the LinkedHashMap, or is mapped to `null`
     linkedHashMap.putIfAbsent("five", 5);
     System.out.println(linkedHashMap);
 }
 }
output:
{one=1, two=2, three=3, four=4, five=5}

Accessing the entries of a LinkedHashMap

This example shows how to

  • containsKey(id):This methods Check if a key exists in a LinkedHashMap.
  • containsValue(name):This method Check if a value exists in the LinkedHashMap.
  • Modify the value associated with a given key in the LinkedHashMap.
 import java.util.LinkedHashMap;
 import java.util.Map;
 import java.util.Iterator;
 public class AccessEntriesFromLinkedHashMapDemo1 {
     public static void main(String[] args) {
         LinkedHashMap customerDetails = new LinkedHashMap<>();
     customerDetails.put(1001, "Virat");     customerDetails.put(1002, "Rohit");     customerDetails.put(1003, "Anil");     customerDetails.put(1004, "Rajesh");     customerDetails.put(1000, "Uday");     System.out.println("customer Details : " + customerDetails);     System.out.println("=== Iterating over a LinkedHashMap using Java 8 forEach and lambda Expression===");      customerDetails.forEach((id, name) -> {         System.out.println(id+" => " + name);     });                             System.out.println("\n=== Iterating over the LinkedHashMap's entrySet using Java 8 forEach and lambda ===");     customerDetails.entrySet().forEach((entry->{         System.out.println(entry.getKey()+" => " +entry.getValue());         })         );     System.out.println("\n=== Iterating over the entrySet of a LinkedHashMap using iterator() ===");     Iterator<Map.Entry<Integer, String>> userCityMappingIterator = customerDetails.entrySet().iterator();     while (userCityMappingIterator.hasNext()) {         Map.Entry<Integer, String> entry = userCityMappingIterator.next();         System.out.println(entry.getKey() + " => " + entry.getValue());     }     System.out.println("\n=== Iterating over the entrySet of a LinkedHashMap using iterator() and forEachRemaining ===");     userCityMappingIterator = customerDetails.entrySet().iterator();     userCityMappingIterator.forEachRemaining(entry -> {         System.out.println(entry.getKey() + " => " + entry.getValue());     }); }
 }
output:
customerIdNameMapping : {1001=Virat, 1002=Rohit, 1003=Anil, 1004=Rajesh, 1005=Uday}
 Found the customer with id 1005 : Uday
 No customer found with name Ram in the map
 Changed the name of customer with id 1004, New mapping : {1001=Virat, 1002=Rohit, 1003=Anil, 1004=Balu, 1005=Uday}

Removing entries from a LinkedHashMap

The example below shows how to

  • Remove a key from a LinkedHashMap.
  • Remove a key from a LinkedHashMap only if it is associated with the given value.
import java.util.LinkedHashMap;
 public class AccessEntriesFromLinkedHashMapDemo2 {
     public static void main(String[] args) {
         LinkedHashMap customerDetails = new LinkedHashMap<>();

     customerDetails.put(1001, "Virat");
     customerDetails.put(1002, "Rohit");
     customerDetails.put(1003, "Anil");
     customerDetails.put(1004, "Rajesh");
     customerDetails.put(1005, "Uday");
     System.out.println("customer Details : " + customerDetails);
    // Remove a key from the LinkedHashMap
     String  name = customerDetails.remove(1004);
     System.out.println("Removed Rajesh " + name   + " from the mapping. New customerDetails : " + customerDetails);
     // Remove a key from the LinkedHashMap only if it is mapped to the given value
     boolean isRemoved = customerDetails.remove(1006, "Sanjay");
     System.out.println("Did John get removed from the mapping? : " + isRemoved);
 }
 }




output:
customer Details : {1001=Virat, 1002=Rohit, 1003=Anil, 1004=Rajesh, 1005=Uday}
 Removed Rajesh Rajesh from the mapping. New customerDetails : {1001=Virat, 1002=Rohit, 1003=Anil, 1005=Uday}
 Did John get removed from the mapping? : false

Iterating over a LinkedHashMap

Iterating over a LinkedHashMap using Java 8 forEach and lambda Expression.

Iterating over the LinkedHashMap’s entrySet using Java 8 forEach and lambda.

Iterating over the entrySet of a LinkedHashMap using iterator().

Iterating over the entrySet of a LinkedHashMap using iterator() and forEachRemaining.

import java.util.LinkedHashMap;
 import java.util.Map;
 import java.util.Iterator;
 public class AccessEntriesFromLinkedHashMapDemo1 {
     public static void main(String[] args) {
         LinkedHashMap customerDetails = new LinkedHashMap<>();
     customerDetails.put(1001, "Virat");
     customerDetails.put(1002, "Rohit"); 
     customerDetails.put(1003, "Anil"); 
     customerDetails.put(1004, "Rajesh");
     customerDetails.put(1000, "Uday");
     System.out.println("customer Details : " + customerDetails);
     System.out.println("=== Iterating over a LinkedHashMap using Java 8 forEach and lambda Expression===");
     customerDetails.forEach((id, name) -> {
         System.out.println(id+" => " + name);
     });
     System.out.println("\n=== Iterating over the LinkedHashMap's entrySet using Java 8 forEach and lambda ===");
     customerDetails.entrySet().forEach((entry->{
         System.out.println(entry.getKey()+" => " +entry.getValue());
         })
         );
     System.out.println("\n=== Iterating over the entrySet of a LinkedHashMap using iterator() ===");
     Iterator<Map.Entry<Integer, String>> customerDetailsIterator = customerDetails.entrySet().iterator();
     while (customerDetailsIterator.hasNext()) {
         Map.Entry<Integer, String> entry =
 customerDetailsIterator.next();
         System.out.println(entry.getKey() + " => " + entry.getValue());
     }
     System.out.println("\n=== Iterating over the entrySet of a LinkedHashMap using iterator() and forEachRemaining ===");
     customerDetailsIterator = customerDetails.entrySet().iterator();
     customerDetailsIterator.forEachRemaining(entry -> {
         System.out.println(entry.getKey() + " => " + entry.getValue());     });
 }
 }

output:

customer Details : {1001=Virat, 1002=Rohit, 1003=Anil, 1004=Rajesh, 1000=Uday}
 === Iterating over a LinkedHashMap using Java 8 forEach and lambda Expression===
 1001 => Virat
 1002 => Rohit
 1003 => Anil
 1004 => Rajesh
 1000 => Uday
 === Iterating over the LinkedHashMap's entrySet using Java 8 forEach and lambda ===
 1001 => Virat
 1002 => Rohit
 1003 => Anil
 1004 => Rajesh
 1000 => Uday
 === Iterating over the entrySet of a LinkedHashMap using iterator() ===
 1001 => Virat
 1002 => Rohit
 1003 => Anil
 1004 => Rajesh
 1000 => Uday
 === Iterating over the entrySet of a LinkedHashMap using iterator() and forEachRemaining ===
 1001 => Virat
 1002 => Rohit
 1003 => Anil
 1004 => Rajesh
 1000 => Uday

read also:

Leave a Reply