Site icon

Insertion order in LinkedHashMap using java (with example)

LinkedHashMap has following attributes.

Constructors of LinkedHashMap are as follows:

Program –  Insertion order of LinkedHashMap in java

package org.learn.collection.map.lhashmap;

import java.util.LinkedHashMap;
import java.util.Map;

public class DemoInsertionOrderLinkedHashMap {

	public static void main(String[] args) {
		Map<Integer, String> mapVehicleNoAndOwner = new LinkedHashMap<>(2,0.75f);
		
		mapVehicleNoAndOwner.put(1000, "Federer");
		mapVehicleNoAndOwner.put(2000, "Bradman");
		mapVehicleNoAndOwner.put(3000, "Jordan");
		mapVehicleNoAndOwner.put(4000, "Woods");
		mapVehicleNoAndOwner.put(5000, "Ali");
		
		System.out.println("1. Iterating LinkedHashMap: ");
		demoIterate_InsertionOrder(mapVehicleNoAndOwner);		
		int key = 1000;
		System.out.printf("2. Accessting value at key: %d is %s\n",key,mapVehicleNoAndOwner.get(key));
		
		key = 3000;
		System.out.printf("3. Accessting value at key: %d is %s\n",key,mapVehicleNoAndOwner.get(key));
		
		System.out.println("4. Iterating LinkedHashMap, insertion order maintained: ");
		demoIterate_InsertionOrder(mapVehicleNoAndOwner);
		
	}

	private static void demoIterate_InsertionOrder(Map<Integer, String> mapVehicleNoAndOwner) {

		mapVehicleNoAndOwner.forEach((key, value) -> {
			System.out.println("Key:"+ key + ", Value:" + value);
		});		
	}
}

Output –  Insertion order of LinkedHashMap in java

1. Iterating LinkedHashMap: 
Key:1000, Value:Federer
Key:2000, Value:Bradman
Key:3000, Value:Jordan
Key:4000, Value:Woods
Key:5000, Value:Ali
2. Accessting value at key: 1000 is Federer
3. Accessting value at key: 3000 is Jordan
4. Iterating LinkedHashMap, insertion order maintained: 
Key:1000, Value:Federer
Key:2000, Value:Bradman
Key:3000, Value:Jordan
Key:4000, Value:Woods
Key:5000, Value:Ali
Exit mobile version