Reputation: 31338
I need a key-value pair data structure which guarantees the retrieval of entries in the order in which they were added, much like ArrayList
or Vector
for just singular entries. Think of it as an ArrayList that enables key-value pairs. Keep in mind, the TreeMap
will not do because the sorting does not go by the value of the key but by the time of insertion. Is there a Java Collection that meets these requirements? I browsed different Map
implementations but couldn't find any that match.
I understand I can define my class that takes the key and the value and put it in an ArrayList but that is only option B to a class described above.
Upvotes: 1
Views: 977
Reputation: 15729
Use java.util.LinkedHashMap
Javadocs here
"This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order)"
Upvotes: 0
Reputation: 16039
I need a key-value pair data structure which guarantees the retrieval of entries in the order in which they were added,
Hash table and linked list implementation of the Map interface, with predictable iteration order.
Upvotes: 4
Reputation: 49432
Are you looking for LinkedHashMap ?
Hash table and linked list implementation of the Map interface, with predictable iteration order.
You can also look into the Guava's ImmutableMap if it suits your purpose.
An immutable, hash-based Map with reliable user-specified iteration order. Does not permit null keys or values.
Upvotes: 6