This is because you are using a Map
without sorting like HashMap
[...] 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.
Instead of this, you can use some concrete implementation like:
TreeMap
:
The map is sorted according to the natural ordering of its keys or by a Comparator provided at map creation time, depending on which constructor is used.
LinkedHashMap
if you need no duplicates...
Hash
table and linked list implementation of the Map
interface, with predictable iteration order.