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
?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With