Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
How to track the order of insertion using Java collections?
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
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
Advertisements
