Access order in LinkedHashMap using java (with example)

By | May 29, 2016

LinkedHashMap have following attributes:

  • LinkedHashMap is Hashtable and LinkedList based implementation of Map interface.
  • By default LinkedHashMap maintains the insertion order (i.e. the order in which elements are added to LinkedHashMap is maintained.)
  • LinkedHashMap has special constructor to create the access order map.
    • Keys are sorted on the basis of access order e.g Invoking the put, putIfAbsent, get, getOrDefault, compute, computeIfAbsent, computeIfPresent, or merge methods results in an access to the corresponding entry.
    • The keys are sorted from least recently accessed used to most recently accessed.
  • Access order feature of LinkedHashMap is used build LRU cache.

Constructor to create access order in LinkedHashMap

  • LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder)
    Constructs an empty LinkedHashMap instance with the specified initial capacity, load factor and ordering mode.

    • if accessOrder is false, then it will result in insertion order
    • if accessOrder is true, then it will result in access Order, One of the important application of access order LinkedHashMap is building LRU cache.

Program – Access order of LinkedHashMap in java


package org.learn.collection.map.lhashmap;

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

public class DemoAccessOrderLinkedHashMap {

	public static void main(String[] args) {
		Map<Integer, String> mapVehicleNoAndOwner = new LinkedHashMap<>(2,0.75f,true);
		
		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 default LinkedHashMap: ");
		demoIterate_AccessOrder(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, least accessed to most accessed keys: ");
		demoIterate_AccessOrder(mapVehicleNoAndOwner);
		
	}

	private static void demoIterate_AccessOrder(Map<Integer, String> mapSportsPersonality) {

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

Output – Access order of LinkedHashMap in java


1. Iterating default 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, least accessed to most accessed keys: 
Key:2000, Value:Bradman
Key:4000, Value:Woods
Key:5000, Value:Ali
Key:1000, Value:Federer
Key:3000, Value:Jordan