Java – LinkedHashMap class

Previous
Next

The only difference between LinkedHashMap and HashMap is, HashMap doesn’t maintain insertion order of elements where as LinkedHashMap does it. LinkedHashMap since jdk 1.4

import java.util.*;
class MapDemo 
{
	public static void main(String[] args) 
{
		LinkedHashMap hm = new LinkedHashMap();
		hm.put(26, "one");
		hm.put(26, "two"); //"one" is replaced with "two"
		hm.put(16, "two"); //duplicate elements allowed
		hm.put(null,"three"); //null key allowed
		hm.put(56,null); //null element allowed
		hm.put("56","four"); //heterogeneous keys allowed
		System.out.println(hm);
	}
}
import java.util.* ;
class MapDemo 
{
	public static void main(String[] args) 
	{
		String s[ ] = { "One", "Two", "Three", "Four" };
		Random r = new Random();

		//HashMap map = new HashMap();
		LinkedHashMap map = new LinkedHashMap();

		for(int i=0 ; i<s.length ; i++)
		{
			int key = r.nextInt(100);
			String ele = s[i] ;
			map.put(key , ele);
			System.out.println(key + " : " + ele);
		}

		// System.out.println("HashMap : "+map); //Doesn't maintain insertion order

		System.out.println("LinkedHashMap : "+map); //Maintain insertion order
	}
}
Previous
Next

Add Comment

Courses Enquiry Form