Collections

How to maintain insertion order of the elements in Java HashMap?

Elements returned from the HashMap while iterating over it might not be in the same order they were inserted. That is because HashMap does not guarantee to maintain the insertion order of the elements. As per the HashMap Java Doc:

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.

How to maintain insertion order of the elements in Java HashMap?

We cannot. As HashMap does not maintain the order of the elements. This means that It might not return the elements in the same order they were inserted into it. If application needs the elements to be returned in the same order they were inserted, LinkedHashMap should be used.

LinkedHashMap implements doubly linked list so that it can traverse through all the elements. As per LinkedHashMap Java Doc:

This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).

In the scenario wherein the HashMap is returned from the third-party library which cannot be changed and application needs ordering of the elements contained in it, LinkedHashMap can be created from the HashMap object. LinkedHashMap has a special constructor for that purpose which takes Map as an argument.

Above given constructor creates an object of LinkedHashMap with the same mappings specified in the original Map object.

Important Note:

LinkedHashMap created in this way maintains the insertion order in which the elements were returned from the HashMap while creation of it (and not the order in which elements were inserted into original HashMap). Let’s see a small example to demonstrate that.

Output

As you can see, we have inserted the Employee objects in HashMap in [emp01, emp03, emp04, emp02] order. However, when we printed the elements by iterating over HashMap, the order was changed to [emp01, emp03, emp02, emp04]. It did not maintain the original insertion order of the elements “emp02” and “emp04”.

Then we created LinkedHashMap object from the original HashMap object and printed it. Which returned the elements in [emp01, emp03, emp02, emp04] order. This is the order in which HashMap returned the elements when LinkedHashMap was created from it. From that point onwards, LinkedHashMap will keep this insertion order whenever it returns the element (not the original order [emp01, emp03, emp02, emp04]).

Here is the example Employee class used in this example.

Please let us know your views in the comments section.

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.