5

I'm looking for a Map implementation that iterates over the key-value pairs in the order in which they were added. For example

Map orderedMap = // instantiation omitted for obvious reasons :)
orderMap.put(4, "d");
orderMap.put(10, "y");
orderMap.put(2, "b");

for (Map.Entry entry : orderedMap.entrySet()) {
  System.out.println(entry.getKey() + ", " + entry.getValue());
}

Will always print

4, d
10, y
2, b

I'm using Java 5.0.

Thanks, Don

Dónal
  • 181,534
  • 169
  • 555
  • 808

1 Answers1

9

That's LinkedHashMap

unbeli
  • 28,007
  • 5
  • 54
  • 55
  • Thanks, I knew there was already something like this in the JDK, but couldn't remember it's name. – Dónal Jul 20 '10 at 10:10
  • 2
    and for the sake of completeness, the other interesting Map implementation in the JDK is TreeMap, which will return the keys in sorted order (2,4,10 in your case). – Thilo Jul 20 '10 at 10:40