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
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.
In Java, we can use LinkedHashMap to keep the insertion order. P.S HashMap does not guarantee insertion order.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With