-2

I have defined a dictionary :

Map<String, Integer>

Then in the code, I am adding entries to the collection :

map.put("> 80", // some stream() + lambda based logic for calculating the value part);
map.put("60 - 80", ....);
map.put("40 - 60", ....);
map.put("20 - 40", ....);
map.put(" < 40", ....);

Later in the debug mode, I see that the ordering of the keys have changed. For e.g. "20 -40" is first, "60- 80" is last. Why is the ordering of keys changing? How can I maintain the ordering of keys in the collection.

Pawan Mishra
  • 7,212
  • 5
  • 29
  • 39
  • 1
    HashMap does not guarantee ordering of keys. If you want to maintain the order of input, use LinkedHashMap – lance-java Feb 26 '15 at 14:36
  • You may want to create a new class let's say `Range` which is comparable, and have a `TreeMap`. It could be more suited for what you need than the traditional answer "use `LinkedHashMap` to maintain insertion order when iterating". – Alexis C. Feb 26 '15 at 14:39
  • The javadoc for HashMap states "This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time. " – Peter Lawrey Feb 26 '15 at 14:42

1 Answers1

4

If you want the ordering of the keys to be maintained you should use a LinkedHashMap which, by default, iterates over the keys according to their insertion order.

Eran
  • 387,369
  • 54
  • 702
  • 768