Easy learning with example program codes

LinkedHashMap in java


LinkedHashMap extends HashMap class and implements the Map interface. It contains the elements in key-value pair form. It maintains insertion order for its elements. It not allowed duplicate key. A LinkedHashMap can have only one null key and multiple null values.

LinkedHashMap example:

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
 * This class is used to show the LinkedHashMap functionality.
 * @author codesjava
public class LinkedHashMapTest {
	public static void main(String args[]){
		//Create LinkedHashMap object.
		Map linkedHashMap = new LinkedHashMap();
		//Add objects to the HashSet.
		linkedHashMap.put(4, "Roxy");
		linkedHashMap.put(2, "Sunil");
		linkedHashMap.put(5, "Sandy");
		linkedHashMap.put(1, "Munish");
		linkedHashMap.put(3, "Pardeep");
		//Print the LinkedHashMap object.
		System.out.println("LinkedHashMap elements:");
		//Get iterator
		Set set=linkedHashMap.entrySet();  
		Iterator iterator=set.iterator();  
		//Print the LinkedHashMap elements using iterator.
		System.out.println("LinkedHashMap elements " +
				"using iterator:");
		   Map.Entry mapEntry=(Map.Entry);  
		   System.out.println("Key: " + mapEntry.getKey() + 
				   ", Value: " + mapEntry.getValue());  


LinkedHashMap elements:
{4=Roxy, 2=Sunil, 5=Sandy, 1=Munish, 3=Pardeep}
LinkedHashMap elements using iterator:
Key: 4, Value: Roxy
Key: 2, Value: Sunil
Key: 5, Value: Sandy
Key: 1, Value: Munish
Key: 3, Value: Pardeep

Download this example.
Next Topic: TreeMap in java with example.
Previous Topic: HashMap in java with example.

Copyright © 2018 CodesJava Protection Status SiteMap