Java -LinkedHashMap class

  •  LinkedHashMap contains values based on the key. It implements the Map interface and extends HashMap class.
  • LinkedHashMap is a Hash table and linked list implementation of the Map interface
  • LinkedHashMap contains only unique elements.
  • LinkedHashMap may have one null key and multiple null values.
  • LinkedHashMap is same as HashMap instead maintains insertion order.
  • LinkedHashMap maintains a doubly-linked list running through all of its entries

 

Example of LinkedHashMap

  1. import java.util.*;
  2. class LinkedHashMapDemo

    {

  3.  public static void main(String args[]){
  4.   LinkedHashMap<Integer,String> hm=new LinkedHashMap<Integer,String>();
  5.   hm.put(100,“A”);
  6.   hm.put(101,“B”);
  7.   hm.put(102,“C”);
  8. for(Map.Entry m:hm.entrySet()){
  9.    System.out.println(m.getKey()+” “+m.getValue());
  10.   }
  11. }
  12. Output:
       100 A
       101 B
       103 C

Another Example of LinkedHashMap

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

         //Adding elements to LinkedHashMap
         lhm.put(22, "A");
         lhm.put(33, "B");
         lhm.put(1, "C");
         lhm.put(2, "D");
         lhm.put(100, "E");

         // Generating a Set of entries
         Set set = lhm.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: A
Key is: 33& Value is: B
Key is: 1& Value is: C
Key is: 2& Value is: D
Key is: 100& Value is: E
 

Leave a comment