LinkedHashMap has following attributes.
- LinkedHashMap maintains the insertion order.
- The default mode is insertion order.
- The order in which elements are added to LinkedHashMap, is maintained
- LinkedHashMap is Hashtable and LinkedList based implementation of Map interface.
Constructors of LinkedHashMap are as follows:
- LinkedHashMap()
Constructs an empty insertion-ordered LinkedHashMap instance with the default initial capacity (16) and load factor (0.75). - LinkedHashMap(int initialCapacity)
Constructs an empty insertion-ordered LinkedHashMap instance with the specified initial capacity and a default load factor (0.75). - LinkedHashMap(int initialCapacity, float loadFactor)
Constructs an empty insertion-ordered LinkedHashMap instance with the specified initial capacity and load factor. - LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder)
Constructs an empty LinkedHashMap instance with the specified initial capacity, load factor and ordering mode. - LinkedHashMap(Map<? extends K,? extends V> m)
Constructs an insertion-ordered LinkedHashMap instance with the same mappings as the specified map.
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