Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Same iteration order on Map.keySet and Map.values?

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?

like image 284
dacwe Avatar asked Sep 05 '12 17:09

dacwe


People also ask

Can a Map have two different values that have the same key?

But the limitation of the Map interface is that multiple values cannot be stored against a single key. To overcome this issue, we can either use Guava Collections or Apache Common Collections. This article has a simple custom implementation that holds multiple values under the same key.

Does Map EntrySet maintain order?

This implementation simply uses table HashMap. Entry[] and returns next element of that table as nextEntry() return value. So if you have HashMap and iterate through its EntrySet elements it will always return them in the same order.

Is keySet an order?

The keySet() method in HashMap returns keys in random order. In LinkedHashMap, it returns keys in insertion order (the same order in which we insert the values), and in TreeMap and SortedMap, it returns keys in sorted order.

Does HashMap iterate in order?

Unlike LinkedHashMap (insertion-order) and TreeMap (key-based order), HashMap does not provide any guarantees of ordering when iterating over the map, e.g. when using a for-each loop, or calling forEach() . Instead, the iteration order of a HashMap depends on internal implementation details.


1 Answers

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.

like image 75
parsifal Avatar answered Sep 30 '22 08:09

parsifal