views:

71

answers:

3

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 "Apple" - Value "3"
Key "Orange" - Value "8"

How do I iterate and get the declared order?

+10  A: 

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)

Bozho
+1  A: 

Use LinkedHashMap

Nivas
+2  A: 

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.

wheaties