How to iterate Linkedhashmap in Java
LinkedHashMap:
- Values will be stored as key value pair as like in HashMap.
- Order of iteration is same as order of insertion. (In HashMap order will not be guaranteed)
- Allows one null key and many null values.
- Duplicates are not allowed and if only the key is duplicate then the value of the respective key will be overridden.
Iterating LinkedHashMap:
[java]
package com.ngdeveloper.com;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
public class HashMapVsLinkedHashMap {
public static void main(String[] args) {
Map<Integer,String> myLinkedHashMap = new LinkedHashMap<Integer,String>();
System.out.println("LinkedHashMap values \n");
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");
myLinkedHashMap.put(6,"null");
myLinkedHashMap.put(null,"null");
for(Entry<Integer,String> myLhm : myLinkedHashMap.entrySet()){
System.out.println(myLhm.getKey()+" "+myLhm.getValue());
}
}
}
[/java]
Output:
LinkedHashMap values
null null
4 struts
5 spring
1 java
2 jsp
3 servlet
6 null