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:

 

package com.javadomain.in;

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());
		}
	}
}

 

Output:
LinkedHashMap values

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

530 total views, 1 views today

Leave a Reply

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