Skip to content

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 the insertion order of the elements in Java HashMap?

We cannot. The HashMap class 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 the application needs the elements to be returned in the same order they were inserted, LinkedHashMap should be used.

The LinkedHashMap class implements a 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, a LinkedHashMap object can be created from the HashMap object. The LinkedHashMap class has a special constructor for that purpose which takes a Map as an argument.

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

Important Note:

The LinkedHashMap object created in this way maintains the insertion order in which the elements were returned from the HashMap while the 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 a 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.

This example is a part of the Java Hashmap tutorial.

Please let me know your views in the comments section.

About the author

Leave a Reply

Your email address will not be published.