How to track the order of insertion using Java collections?

Java 8Object Oriented ProgrammingProgramming

To track the order of insertion, you can use Map.Entry() in case of a Map. Let’s say we have the following LinkedHashMap −

Map<String, Integer>map = new LinkedHashMap<>();
map.put("Jack", 0);
map.put("Tim", 1);
map.put("David", 2);
map.put("Tom", 3);
map.put("Kevin", 4);
map.put("Jeff", 5);

Now, loop through Map.Entry and get the order of insertion correctly with Key and Value −

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

Example

 Live Demo

import java.util.LinkedHashMap;
import java.util.Map;
public class Demo {
   public static void main(String[] args) {
      Map<String, Integer>map = new LinkedHashMap<>();
      map.put("Jack", 0);
      map.put("Tim", 1);
      map.put("David", 2);
      map.put("Tom", 3);
      map.put("Kevin", 4);
      map.put("Jeff", 5);
      map.put("Katies", 6);
      map.put("Steve", 7);
      map.put("Andrew", 8);
      map.put("Angelina", 9);
      for (Map.Entry<String, Integer>entry: map.entrySet()) {
         System.out.println(entry.getKey() + " => " + entry.getValue());
      }
   }
}

Output

Jack => 0
Tim => 1
David => 2
Tom => 3
Kevin => 4
Jeff => 5
Katies => 6
Steve => 7
Andrew => 8
Angelina => 9
raja
Published on 25-Apr-2019 09:27:00
Advertisements