LinkedHashMap in java

In the previous post, we have seen how to remove elements from HashMap. In this post, we will learn about LinkedHashMap in java.

LinekdHashMap has the following features.

  • It implements Map and extends HashMap.
  • It differs from HashMap where it maintains a doubly-linked list running through all of its entries.This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).
  • It maintains the insertion order , where HashMap does not.

Let’s understand LinkedHashMap in java.

Example:

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

public class HashMapEx {

	public static void  main(String[] args){
		
		LinkedHashMap<Integer,String> hm = new LinkedHashMap<Integer,String>();
		hm.put(15, "Mobile");
		hm.put(6, "TV");
		hm.put(10, "Laptop");
		hm.put(2, "Desktop");
		hm.put(1, "Tablet");
		hm.put(23, "Microphone");
		
		Iterator iter = hm.entrySet().iterator();
		while(iter.hasNext()){
			Map.Entry m = (Entry) iter.next();
			//Maintains insertion order
			System.out.println(m.getKey()+"--"+m.getValue()); 
		}
		
	}
}

Output:

15–Mobile
6–TV
10–Laptop
2–Desktop
1–Tablet
23–Microphone


 

Questions/Suggestions
Have any question or suggestion for us?Please feel free to post in Q&A Forum
Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".