Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maps (collection) that maintains insertion Order in java

I need to use Maps in Java for an Android Application. But the problem is that the list gets sorted automatically. How do I use Maps to get the data in the same order as I have inserted data.

like image 298
Akhil K Nambiar Avatar asked Mar 04 '12 06:03

Akhil K Nambiar


People also ask

Which map maintains insertion order in Java?

Java LinkedHashMap It maintains a linked list of the entries in the map, in the order in which they were inserted. This allows insertion-order iteration over the map. That is,when iterating through a collection-view of a LinkedHashMap, the elements will be returned in the order in which they were inserted.

Does map maintain order in Java?

HashMap does not maintains insertion order in java. Hashtable does not maintains insertion order in java. LinkedHashMap maintains insertion order in java. TreeMap is sorted by natural order of keys in java.

Does map entrySet maintain order?

According to the Javadocs, yes. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).


2 Answers

You should use LinkedHashMap for this purpose..Visit Android Docs and Java Docs for more details.

like image 75
Shashank Kadne Avatar answered Oct 15 '22 10:10

Shashank Kadne


The LinkedHashMap maintains insertion order.

like image 26
Nadir Muzaffar Avatar answered Oct 15 '22 12:10

Nadir Muzaffar