LinkedHashMap Class in Java

LinkedHashMap Class

The LinkedHasMap class extends the HashMap and implements the Map interface. The implementation of LinkedHashMap is different from HashMap in the way that it maintains a doubly-linked list. It doesn’t contain duplicate value. It allows to insert one null key and multiple null values.

Example: Program to implement methods in LinkedHashMap class


import java.util.*;
public class LinkedHashMapDemo
{
      public static void main(String args[])
      {
         //creates LinkedhashMap
         LinkedHashMap<Integer, String> lhm = new LinkedHashMap<Integer, String>();
         System.out.println("Initial size of LinkedHashMap: "+lhm.size());

         //insert the element in LinkedHashMap
         lhm.put(1,"SS");
         lhm.put(3,"AA");
         lhm.put(4, "CC");
         lhm.put(new Integer(5), "MM");
         lhm.put(new Integer(2), new String("EE"));
         lhm.put(null, null);
         lhm.put(null, "HH");
         Set set = lhm.entrySet();
         Iterator i = set.iterator();

         // Display the elements
         System.out.println("Elements of LinkedHashMap:");
         while(i.hasNext())
         {
               Map.Entry me = (Map.Entry)i.next();
               System.out.print(me.getKey() + ": ");
               System.out.println(me.getValue());
         }
         System.out.println("SIze of LinkedHashMap after adding: "+lhm.size());
         System.out.println("LinkedHashMap is empty: "+lhm.isEmpty());
      }
}


Output:
Initial size of LinkedHashMap: 0
Elements of LinkedHashMap:
1: SS
3: AA
4: CC
5: MM
2: EE
null: HH
SIze of LinkedHashMap after adding: 6
LinkedHashMap is empty: false