Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iteration order of java.util.HashMap.values()

Tags:

java

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()));
    }
}
like image 996
Vytenis Bivainis Avatar asked Dec 09 '22 01:12

Vytenis Bivainis


1 Answers

From the doc of 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.

If you look at its code, you will find out that once you call put(), eventually hash is calculated, entry object is created and added into a bucket array. I have over simplified the purpose of the code just to explain what happens behind the scene.

If you want guaranteed order, use LinkedHashMap or TreeMap depending on your requirements

Also check,

Difference between HashMap, LinkedHashMap and TreeMap

like image 200
sam Avatar answered Dec 21 '22 19:12

sam