How to preserve insertion order in HashMap?

JavaHashmap

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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 - Java

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionrealteboView Question on Stackoverflow
Solution 1 - JavaNPEView Answer on Stackoverflow
Solution 2 - Javanicholas.hauschildView Answer on Stackoverflow