javasortinghashmapsetentryset

The Set returned from HashMap.entryset(), how is it sorted?


I need to replicated the sorting I get on a set returned from the function entrySet() from the HashMap class. I don't understand how it is sorted.

The following code:

HashMap<String, Integer> testList = new HashMap<String, Integer>();
testHash.put("B", 1);
testList.put("A", 3);
testList.put("E", 2);
testList.put("D", 5);
testList.put("C", 4);

//testList.put("B", 1);
//testList.put("C", 4);
//testList.put("A", 3);
//testList.put("E", 2);
//testList.put("D", 5);

for (Map.Entry<String, Integer> entry : testList.entrySet()) {
    System.out.println(entry.getKey() + " - " + entry.getValue());
}

Returns:

D - 5
E - 2
A - 3
B - 1
C - 4

Why? The out-commented code returns them in the same order.


Solution

  • I don't understand how it is sorted.

    That is because it does not follow any particular order. The actual ordering depends on the hash codes of the items that you put in, on the order in which you put them in, and on the number of hash buckets (closely connected to load factor).

    No matter in which order I put the items in the HashMap, it always returns them in the same order.

    That is because the number of items is the same, hash codes of items are the same, and you did not encounter an order that results in output reordering due to hash collisions.

    It is possible to construct an ordering that would produce a slightly different output for the same group of items. The take-away lesson, however, is that the order is not reliable, so you should not expect your items to come in any particular order.

    If you must maintain a specific order, Java offers two good choices: