3

I upgraded from Java 7 to Java 8 and noticed Junit failures in places where the keySet() of HashMap was used.

Map<String, String> map = new HashMap<String, String>();
map.put("var1".toUpperCase(), "var");
map.put("var".toUpperCase(), "var1");
Set<String> varKeys = replacementMap.keySet();

In Java 7:

varKeys=[VAR,VAR1]

In Java 8:

varKeys=[VAR1,VAR]

Any help on this?

Divya Dev
  • 125
  • 9

4 Answers4

15

HashMap does not guarentee order of keys. If your Junit test relied on the order of keys, then it is designed incorrectly.

Manu
  • 1,474
  • 1
  • 12
  • 18
Sharon Ben Asher
  • 13,849
  • 5
  • 33
  • 47
6

I suggest using LinkedHashMap instead if you want to preserve insertion order.

The order of HashMap isn't defined and isn't consistent. i.e. the same keys can appear in different orders. The implementation of HashMap changed between Java 7 and Java 8 significantly so you should expect the order to be different in some cases.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
3

Set doesn't guarantee order of elements. If you need ordered hashmap, you can use LinkedHashMap

TheKojuEffect
  • 20,103
  • 19
  • 89
  • 125
3

That's a HashSet/HashMap, where order is never guaranteed and can change at any time. What you want is TreeSet or LinkedHashSet, learn here about differences.

agilob
  • 6,082
  • 3
  • 33
  • 49