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.
3 Answers 3
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:
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 theMap
interface, with predictable iteration order.
-
1ok thanks, i'll change the codeCiurga– Ciurga2016年06月15日 08:30:25 +00:00Commented Jun 15, 2016 at 8:30
-
@Ciurga if you need to loop them mantaining the order and you don't need to access them by key consider to use a List instead.Davide Lorenzo MARINO– Davide Lorenzo MARINO2016年06月15日 08:34:29 +00:00Commented Jun 15, 2016 at 8:34
-
@Ciurga as this is your first question you must know if this or any answer has solved your question please consider accepting it by clicking the check-mark. This indicates to the wider community that you've found a solution and gives some reputation to both the answerer and yourself. There is no obligation to do this.Jordi Castilla– Jordi Castilla2016年06月15日 09:52:28 +00:00Commented Jun 15, 2016 at 9:52
If you want predictable iteration order (insertion order) then use a LinkedHashMap
If you want the elements to be sorted you need to use a TreeMap , in this case the Keys need to implement Comparable interface
Either change the Map implementation into one of the ones that support ordering or sort the keys before iterating over them. I am a bit confused though, normally one gets the keys of a map by the keySet
method. I am not familiar with stringPropertyNames
but if it is a Map you should be able to do something like (untested code):
List<String> keys = new ArrayList(mymap.keySet());
Collections.sort(keys);
for (String key : keys) {
[...]
}
mymap
is.Map
that respects the order in which the elements were originally inserted, such asLinkedHashMap
, or do you want aMap
which sorts the keys in a particular order, such asTreeMap
?