Java

How To Use LinkedHashMap In Java?

A Hash table and linked list implementation of the Map interface with a predetermined iteration sequence is called LinkedHashMap. In contrast to HashMap, this version keeps a doubly-linked list extending across each entry. This linked list specifies the iteration ordering, which often corresponds to the order in which the map’s keys were added (insertion-order). HashMap and TreeMap have been explored in recent lessons. The difference between this class and the others is:

  • HashMap doesn’t keep any kind of order.
  • Ascending key order is used by TreeMap to arrange the entries.
  • The insertion order is maintained by LinkedHashMap.

Let’s use an example to better understand the LinkedHashMap:

import java.util.LinkedHashMap;
import java.util.Set;
import java.util.Iterator;
import java.util.Map;
public class LinkedHashMapDemo {
    public static void main(String args[]) {
         // HashMap Declaration
         LinkedHashMap<Integer, String> lhmap = 
                 new LinkedHashMap<Integer, String>();

         //Adding elements to LinkedHashMap
         lhmap.put(22, "Abey");
         lhmap.put(33, "Dawn");
         lhmap.put(1, "Sherry");
         lhmap.put(2, "Karon");
         lhmap.put(100, "Jim");

         // Generating a Set of entries
         Set set = lhmap.entrySet();

         // Displaying elements of LinkedHashMap
         Iterator iterator = set.iterator();
         while(iterator.hasNext()) {
            Map.Entry me = (Map.Entry)iterator.next();
            System.out.print("Key is: "+ me.getKey() + 
                    "& Value is: "+me.getValue()+"\n");
         }
    }
}

Output:

Key is: 22& Value is: Abey
Key is: 33& Value is: Dawn
Key is: 1& Value is: Sherry
Key is: 2& Value is: Karon
Key is: 100& Value is: Jim

Related Articles

Leave a Reply

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

Back to top button