Java Collection How to - Track the order of insertion using collections








Question

We would like to know how to track the order of insertion using collections.

Answer

import java.util.LinkedHashMap;
import java.util.Map;
/*from   www . j av a2s  . c o  m*/
public class Main {
  public static void main(String[] args) {
    Map<String, Integer> map = new LinkedHashMap<>();

    map.put("Zero", 0);
    map.put("One", 1);
    map.put("Two", 2);
    map.put("Three", 3);
    map.put("Four", 4);

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

The code above generates the following result.