javamaps

java - how to iterate through maps in order


This is the code:

for(String key : mymap.stringPropertyNames()) {
//mycode
}

This works correctly but I noticed I get the values I need in random order, is there a way to loop through the map using a particular order?

EDIT: Mymap is a properties object.


Solution

  • 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.