How to preserve insertion order in HashMap?
Solution 1
LinkedHashMap
is precisely what you're looking for.
It is exactly like HashMap
, except that when you iterate over it, it presents the items in the insertion order.
Solution 2
HashMap
is unordered per the second line of the documentation:
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.
Perhaps you can do as aix suggests and use a LinkedHashMap
, or another ordered collection. Take a look on javapractices.com's guide on Choosing the right Collection.
realtebo
italian programmer with a lot of experience in - php [Laravel, Yii Framework] - sql - .NET (C# and VB) - javascript [VueJs, jQuery] Base knowledge of Android and Windows Apps developing
Updated on December 16, 2021Comments
-
realtebo over 2 years
I'm using a
HashMap
. When I iterate over the map, the data is returned in (often the same) random order. But the data was inserted in a specific order, and I need to preserve the insertion order. How can I do this? -
Xenione over 10 yearsaccording to java doc it says: This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map.¿¿¿¿¿ NORMALLY ????? what does it mean? the order insertion is not garantee....
-
NPE over 10 years@Xenione: You get to choose between insertion order and access order. See the last argument to bit.ly/1jZXlCl
-
Nahuel Fouilleul over 8 years@Xenione [Note that insertion order is not affected if a key is re-inserted into the map], when a key is put twice the second put doesn't change the order so iterating order is not exactly the insert order because of unicity of keys; normally means if keys are unique
-
Nahuel Fouilleul over 8 yearsconstructors give a "insert order" Map, but constructor (int,float,boolean), if third argument is true allows to create "access order" LinkedHashMap in this case the call of get will affect order, the order is the least accessed first
-
Mushy almost 8 yearsThis makes using
java.util.Comparator<T>
withjava.util.Collections.sort()
explicitly unnecessary and thank you for providing very helpful information. -
Vitaliy Terziev over 6 yearsfaster as well, thanks
-
Kumaresan Perumal about 3 yearsgreat answer...