Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i parse a map (foreach) in the same order i created it (JAVA)

So i have a map that i created (inserted data) in an order i wanted. When parsing the map the 1st key returned in foreach is not the first key i inserted. Is there a way for that to happen?

Also sorting my map is kinda tricky cause it has to be sorted by Value and in specific field within the Value. Ty

like image 794
weakwire Avatar asked May 22 '10 23:05

weakwire


People also ask

Does map entrySet maintain order?

A LinkedHashMap is the same as a regular HashMap , except that a LinkedHashMap maintains the insertion order, whereas a HashMap does not. Internally, the LinkedHashMap uses a doubly-linked list to maintain the insertion order.

How do you keep an insertion order on a map?

In Java, we can use LinkedHashMap to keep the insertion order. P.S HashMap does not guarantee insertion order.

Can we maintain order in map?

So, if you want to keep the elements in the order that they were inserted, use another implementation of Map. Use LinkedHashMap, which keeps that order.


1 Answers

Check out LinkedHashMap for a Map implementation with predictable iteration order. You also might consider just using a List if you're not actually doing lookup by keys.

like image 79
David Winslow Avatar answered Sep 30 '22 19:09

David Winslow