Is it guaranteed that keys and values in standard implementations of java.util.Map
are returned in the same order? For example, if map contains mapping x1 -> y1
and x2 -> y2
, then if keySet()
iteration yields x1, x2
, is it guaranteed that values()
iteration will yield y1, y2
and not y2, y1
? I haven't seen anywhere guaranteed that this is true, but it seems to work. Could anyone give confirm or deny this premise and give counterexample?
public class MapsTest {
@Test
public void hashMapKeysAndValuesAreInSameOrder() {
assertKeysAndValuesAreInSameOrder(new HashMap<>());
}
@Test
public void treeMapKeysAndValuesAreInSameOrder() {
assertKeysAndValuesAreInSameOrder(new TreeMap<>());
}
private void assertKeysAndValuesAreInSameOrder(Map<Integer, Integer> map) {
Random random = new Random();
IntStream.range(0, 100000).map(i -> random.nextInt()).forEach(i -> map.put(i, i));
assertEquals(new ArrayList<>(map.keySet()), new ArrayList<>(map.values()));
}
}