Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stable element ordering issue while iterating HashMap in Java 8

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 ?

like image 432
Siddhartha Avatar asked May 14 '16 13:05

Siddhartha


1 Answers

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.

like image 73
Mifeet Avatar answered Sep 20 '22 12:09

Mifeet