Reputation: 43504
For a map like:
Map<Integer, Integer> map = ...;
map.put(1, 1);
map.put(2, 2);
map.put(3, 3);
map.put(4, 4);
Is this code...
for (Integer i : map.keySet()) System.out.println(i);
for (Integer i : map.values()) System.out.println(i);
...guaranteed print the same same sequence twice?
If not, are there any guarantees in for example java.util.HashMap
?
Upvotes: 16
Views: 7195
Reputation: 1102
Yes. Sort of. You can use a subclass of SortedMap, i.e. TreeMap. That will keep keys in a natural order. (or you can give it a specific comparator). But when you use tree map, you HAVE to make sure the compareTo method "must be consistent with equals". Read the javadocs for more details. But in short, yes, you CAN sort a map.
Upvotes: -1
Reputation: 66647
No, not guaranteed. One is Set
and one is Collection
, neither guarantee the order.
If you would like to keep order. May be LinkedHashMap()
with entrySet()
help you.
Upvotes: 7
Reputation: 592
No, there is no guarantee, although in practice it will happen (there's no good reason for the map to use a different iterator for the keys and values).
If you want to guarantee iteration order, iterate the entrySet()
:
for (Map.Entry<Integer,Integer> entry : map.entrySet())
// ...
Since you ask about HashMap
, note also that any changes to the map will potentially change iteration order, as a result of the mapbeing rehashed.
Upvotes: 18