Sorted hashmap iteration

A HashMap by definition doesn't have an order. If you need to preserve or create some kind of order you need to use TreeMap instead of HashMap.


A HashMap doesn't have any order. If you want insertion order, use a LinkedHashMap. If you want keys sorted using their natural ordering or a custom comparator, use a TreeMap.


HashMap doesn't have an order. You can't even guarentee that two HashMaps with the same keys will have the same order.

If you want an order using TreeMap or LinkedHashMap and the iterator will be in the order the collection provides.


Note: In some situations the keys will be sorted, so the keys are not even guarenteed to be random.

HashMap<Integer, String> map = new HashMap<>();
for(int i=0;i<10;i++)
    map.put(i, ""+i);
System.out.println(map.keySet());

prints

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Tags:

Java