Open In App

How does the ‘accessOrder’ Configuration in LinkedHashMap Work?

In Java Programming, LinkedHashMap is a pre-defined class, and it can be extended HashMap. It provides the hash table with a predictable iteration order. LinkedHashMap is a part of the java.util package and it maintains a doubly linked list.

In this article, we will learn how the accessOrder configuration in LinkedHashMap works in Java.



Syntax:

LinkedHashMap<K, V> map = new LinkedHashMap<>(initialCapacity, loadFactor, accessOrder);

Step-by-Step Implementation

Note: LinkedHashMap elements will be printed based on the access order you can perform on the LinkedHashMap then first access element will be print first second access be second etc.



Program to Know the Working of accessOrder Configuration in LinkedHashMap in Java

Below is the code implementation of accessOrder configuration in LinkedHashMap.




// Java program of accessOrder configuration in LinkedHashMap 
import java.util.LinkedHashMap;
import java.util.Map;
  
public class GfGAccessOrder {
    public static void main(String[] args) 
    {
        // creating a LinkedHashMap with access order enabled
        Map<Integer, String> linkedHashMap = new LinkedHashMap<>(16, 0.75f, true);
  
        // adding entries to the map
        linkedHashMap.put(1, "One");
        linkedHashMap.put(2, "Two");
        linkedHashMap.put(3, "Three");
  
        // accessing entry 1
        linkedHashMap.get(2);
  
        // accessing entry 2
        linkedHashMap.get(1);
  
        // accessing entry 3
        linkedHashMap.get(3);
  
        // iterating over the map to demonstrate access order
        System.out.println("Entries in LinkedHashMap with access order:");
        for (Map.Entry<Integer, String> entry : linkedHashMap.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}

Output
Entries in LinkedHashMap with access order:
2: Two
1: One
3: Three

Explanation of the Program:

The above program is an example of access order configuration in LinkedHashMap. Enabling access order is the creation of the instance of the LinkedHashMap.

 Map<Integer, String> linkedHashMap = new LinkedHashMap<>(16, 0.75f, true);

If we observe, the creation of the LinkedHashMap contains three parameters:

In the above program, which one will be accessed first, once we set the access order to true, values will print based on the access order into the program.


Article Tags :