Friday 8 September 2017

Get elements of LinkedHashMap by access order?

By default LinkedHashMap stores elements in the order they inserted. LinkedHaspMap provides a constructor, that is used to get the elements of LinkedHashMap in their access order, that is from least-recently accessed to most-recently (access-order).

public LinkedHashMap(int initialCapacity, float loadFactor,boolean accessOrder)
Above constructor is used to define a access-order linked hash map. If the argument 'accessOrder' is true, then it constructs linked hash map using access order of the keys, else insertion order of the keys.

Example
Map<Integer, String> map = new LinkedHashMap<>(10, 0.75f, true);

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

public class Test {

 private static void printMap(Map<Integer, String> map) {

  System.out.println("\n***************************************");
  for (Map.Entry<Integer, String> entry : map.entrySet()) {
   System.out.println(entry.getKey() + " : " + entry.getValue());
  }
  System.out.println("***************************************");

 }

 public static void main(String args[]) {
  Map<Integer, String> map = new LinkedHashMap<>(10, 0.75f, true);

  map.put(1, "Krishna");
  map.put(2, "Hari");
  map.put(3, "Ram");
  map.put(4, "Joel");

  printMap(map);

  System.out.println("\nAccessing the key 1");
  map.get(1);

  printMap(map);

  System.out.println("\nAccessing the key 3");
  map.get(3);
  printMap(map);

 }
}


Output
***************************************
1 : Krishna
2 : Hari
3 : Ram
4 : Joel
***************************************

Accessing the key 1

***************************************
2 : Hari
3 : Ram
4 : Joel
1 : Krishna
***************************************

Accessing the key 3

***************************************
2 : Hari
4 : Joel
1 : Krishna
3 : Ram
***************************************

After inserting the elements, those are maintained in same order.

1 : Krishna
2 : Hari
3 : Ram
4 : Joel

After accessing the key '1' from linked hashmap.
2 : Hari
3 : Ram
4 : Joel
1 : Krishna

After accessing the key '3'.

2 : Hari
4 : Joel
1 : Krishna

3 : Ram

You may like



No comments:

Post a Comment