Iterating through a map's contents as declared
How do I get the values of a Map
in the way they were declared?
If map's contents are-
Key "Apple" - Value "3"
Key "Banana" - Value "4"
Key "Orange" - Value "8"
I don't want to get-
Key "Banana" - Value "4"
Key "Ap开发者_如何学运维ple" - Value "3"
Key "Orange" - Value "8"
How do I iterate and get the declared order?
Map
implementations are not required to preserve insertion order. The most used - HashMap
does not, for example.
You can use java.util.LinkedHashMap
, which does.
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)
Are you asking about making the container return objects to you in a custom order, such as alphabetical or are you looking for insertion order? Others have already suggested the solution to insertion order. I've upvoted them.
If that's not what you want may I suggest you look at SortedMap, TreeMap, NavigableMap, and their ilk. There you can make a custom comparator which will return to you the ordering of your choice. If you don't make a comparator, it'll default to a less than comparison on the key objects.
Use LinkedHashMap
精彩评论