Some test cases are failing in my application which depends upon the element insertion order . It used to work fine in Java 7 but this issue started after upgrading to Java 8. While searching internet I found this in an article:
Java 8 includes some possible changes to HashSet/Map iteration order:
Can some please suggest me - how can I iterate the objects in a Map in the same order as the insertion order into the Map, considering I would still be using Java 1.8 in my dev environment?
Yes of course it was never assured by HashMap that the objects can be retrieved in the same order , but yes it used to work in java 7.
Does LinkedHashMap
work to implement this ?
Yes, you must use LinkedHashMap
which has a stable iteration order even across Java versions, as enforced by its contract:
This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). Note that insertion order is not affected if a key is re-inserted into the map.
On several occasions, we also needed repeatable iteration order across different Java versions and LinkedHashMap
worked just fine.
TreeMap
would also be a solution for stable iteration order. Of course, it has a logarithmic operation time (as opposed to constant in LinkedHashMap
) and the iteration order is not insertion order but key order:
The map is ordered according to the natural ordering of its keys, or by a Comparator typically provided at sorted map creation time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With