Home » Java » How to preserve insertion order in HashMap? [duplicate]

How to preserve insertion order in HashMap? [duplicate]

Posted by: admin November 2, 2017 Leave a comment

Questions:

This question already has an answer here:

Answers:

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.

Questions:
Answers:

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. This link can help you find the most appropriate collection to use.