-4

Why does HashMap returning values out of order?

public class Main {
    public static void main(String[] args) {
        Map<Integer, String> hashMap = new HashMap<>();
        hashMap.put(40, "40");
        hashMap.put(10, "10");
        hashMap.put(30, "30");
        hashMap.put(20, "20");

        System.out.println(hashMap);
    }
}

Output:

{20=20, 40=40, 10=10, 30=30}

I expected:

{40=40, 10=10, 30=30, 20=20}

Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
High hopes
  • 55
  • 7
  • It is showing you the key-value relationship in a readable form. key = value – rabowlen Jan 30 '20 at 21:32
  • What specifically needs explaining? – Dave Newton Jan 30 '20 at 21:33
  • It would be better if you explained what your desired output was. Its only just showing the key, value pairs that you put on your map – Risalat Zaman Jan 30 '20 at 21:33
  • 5
    A Hashmap does not maintain insertion order, a LinkedHashMap will – Kevvvvyp Jan 30 '20 at 21:37
  • My guess is that the OP is surprised about the _order_ in which the key-value couples are presented. I'm not sure about Java, but in Python dictionaries are not guaranteed to mantain the same insertion order. I suppose it is the same in java. – Roberto Caboni Jan 30 '20 at 21:38
  • @DaveNewton about order – High hopes Jan 30 '20 at 21:38
  • See [Java class that implements Map and keeps insertion order](https://stackoverflow.com/questions/683518/java-class-that-implements-map-and-keeps-insertion-order) for more info on other maps that maintain ordering. HashMap in particular says this on its javadoc page: "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." – azurefrog Jan 30 '20 at 21:38
  • Here's another tutorial of information regarding the difference between the forms of Maps in Java: [HashMap vs TreeMap vs HashTable vs LinkedHashMap](https://www.programcreek.com/2013/03/hashmap-vs-treemap-vs-hashtable-vs-linkedhashmap/) – Tim Hunter Jan 30 '20 at 21:40

3 Answers3

4

A HashHap is unordered. So there is no particular order in which the key value pairs will be represented by toString().

The toString() method of HashMap, which is called by System.out.println, is implemented to represent the map as String like this:

{key0=value0, key1=value1,..., keyN=valueN}

The order can but is not guaranteed to to be the order of insertion.

Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
4

The implementation of the map interface that you are using here (HashMap) does not maintain the order of insertion. You need to use something like LinkedHashMap or TreeMap. Hopefully this answer will help you more Java Class that implements Map and keeps insertion order?

Risalat Zaman
  • 1,189
  • 1
  • 9
  • 19
0

You are calling the toString method from the hashmap, not actually getting the values, you should get the values using get

hashMap.get(10);
Colby Quinn
  • 138
  • 2
  • 8