Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

Java – LinkedHashMap

Declaration

class LinkedHashMap<K,V>

The LinkedHashMap class extends HashMap class.

It uses hash-table + linked-list as a data structure to store the map.

LinkedHashMap maintains insertion order of its elements.

It can contain only one null Key and many null values.

K specifies key.

V specifies value.

List of LinkedHashMap Constructors (CLICK HERE)

List of LinkedHashMap Methods (CLICK HERE)

Non Generic Demo

Non generic LinkedHashMap can contain any type of keys & values.

Example

 import java.util.Iterator;
 import java.util.LinkedHashMap;
 import java.util.Map;
 import java.util.Set;

 public class NonGenericLinkedHashMapDemo 
 {
     public static void main(String args[]) 
     {
         LinkedHashMap lhm = new LinkedHashMap();
         lhm.put("James",55000);
         lhm.put("Rohit",66000);
         lhm.put("Poonam",77000);
         lhm.put("Daisy", 88000);
         lhm.put("Ricky", 99000);
	      
         System.out.println(lhm);
	      
         System.out.println("\n After using Iterator :: ");
	      
         Set s = lhm.entrySet();
         Iterator itr = s.iterator();
	      
         while(itr.hasNext())
         {
             Map.Entry m = (Map.Entry)itr.next();
             System.out.println("Salary of "+m.getKey() + " is "+m.getValue());
         }
     }
 }

Output

{James=55000, Rohit=66000, Poonam=77000, Daisy=88000, Ricky=99000}

After using Iterator ::
Salary of James is 55000
Salary of Rohit is 66000
Salary of Poonam is 77000
Salary of Daisy is 88000
Salary of Ricky is 99000

Generic Demo

Generic type LinkedHashMap allows storing keys & values only of type, specified during declaration.

Example

 import java.util.Iterator;
 import java.util.LinkedHashMap;
 import java.util.Map;
 import java.util.Map.Entry;
 import java.util.Set;

 public class GenericLinkedHashMapDemo 
 {
     public static void main(String args[]) 
     {
         LinkedHashMap<String, Integer> lhm = new LinkedHashMap<String, Integer>();
         lhm.put("James",55000);
         lhm.put("Rohit",66000);
         lhm.put("Poonam",77000);
         lhm.put("Daisy",88000);
         lhm.put("Ricky",99000);
	      
         System.out.println(lhm);
	      
         System.out.println("\n After using Iterator :: ");
	      
         Set<Map.Entry<String, Integer>> s = lhm.entrySet();
         Iterator<Entry<String, Integer>> itr = s.iterator();
	      
         while(itr.hasNext())
         {
             Map.Entry<String, Integer> m = (Entry<String, Integer>)itr.next();
             System.out.println("Salary of "+m.getKey() + " is "+m.getValue());
         }
     }
}

Output

{James=55000, Rohit=66000, Poonam=77000, Daisy=88000, Ricky=99000}

After using Iterator ::
Salary of James is 55000
Salary of Rohit is 66000
Salary of Poonam is 77000
Salary of Daisy is 88000
Salary of Ricky is 99000

 

Leave a reply