Difference between Hashmap and Linkedhashmap in Java

HashMap and LinkedHashMap:

HashMap:

  • Order will not be guaranteed.
  • Allows one null key and many null values.
  • It will not allow the duplicates, if only the key is duplicate then value be overridden.

LinkedHashMap:

  • Order of iteration will be same as order of insertion. (insertion order)
  • Allows one null key and many null values as like HashMap.
  • It will not allow the duplicates, if only the key is duplicate then value be overridden.

The below program gives the practical explanation for the above points,

[java]
package com.ngdeveloper.com;

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

public class HashMapVsLinkedHashMap {

public static void main(String[] args) {
Map<Integer,String> myHashMap = new HashMap<Integer,String>();
System.out.println("HashMap values");
myHashMap.put(4,"ajax");
myHashMap.put(5,"jquery");
myHashMap.put(1,"java");
myHashMap.put(2,"jsp");
myHashMap.put(3,"servlet");
myHashMap.put(4,"struts");
myHashMap.put(5,"spring");
myHashMap.put(null,"null");
myHashMap.put(null,"null");
for(Entry<Integer,String> myLhm : myHashMap.entrySet()){
System.out.println(myLhm.getKey()+" "+myLhm.getValue());

}

System.out.println("\n\n");

Map<Integer,String> myLinkedHashMap = new LinkedHashMap<Integer,String>();
System.out.println("LinkedHashMap values");
myLinkedHashMap.put(null,"null");
myLinkedHashMap.put(null,"null");
myLinkedHashMap.put(4,"ajax");
myLinkedHashMap.put(5,"jquery");
myLinkedHashMap.put(1,"java");
myLinkedHashMap.put(2,"jsp");
myLinkedHashMap.put(3,"servlet");
myLinkedHashMap.put(4,"struts");
myLinkedHashMap.put(5,"spring");
myHashMap.put(6,"null");
myHashMap.put(null,"null");

for(Entry<Integer,String> myLhm : myLinkedHashMap.entrySet()){
System.out.println(myLhm.getKey()+" "+myLhm.getValue());
}
}
}
[/java]

Output:
HashMap values
null null
1 java
2 jsp
3 servlet
4 struts
5 spring

LinkedHashMap values
null null
4 struts
5 spring
1 java
2 jsp
3 servlet
6 null

Leave a Reply