Java Class that implements Map and keeps insertion order?
I'm looking for a class in java that has key-value association, but without using hashes. Here is what I'm currently doing:
Hashtable
. Hashtable.entrySet()
. Map.Entry
for the iterator. Module
(a custom class) based on the value. The problem with this is that I do not have control over the order that I get the values back, so I cannot display the values in the a given order (without hard-coding the order).
I would use an ArrayList
or Vector
for this, but later in the code I need to grab the Module
object for a given Key, which I can't do with an ArrayList
or Vector
.
Does anyone know of a free/open-source Java class that will do this, or a way to get values out of a Hashtable
based on when they were added?
Thanks!
I suggest a LinkedHashMap
or a TreeMap
. A LinkedHashMap
keeps the keys in the order they were inserted, while a TreeMap
is kept sorted via a Comparator
or the natural Comparable
ordering of the elements.
Since it doesn't have to keep the elements sorted, LinkedHashMap
should be faster for most cases; TreeMap
has O(log n)
performance for containsKey
, get
, put
, and remove
, according to the Javadocs, while LinkedHashMap
is O(1)
for each.
If your API that only expects a predictable sort order, as opposed to a specific sort order, consider using the interfaces these two classes implement, NavigableMap
or SortedMap
. This will allow you not to leak specific implementations into your API and switch to either of those specific classes or a completely different implementation at will afterwards.
If an immutable map fits your needs then there is a library by google called guava (see also guava questions)
Guava provides an ImmutableMap with reliable user-specified iteration order. This ImmutableMap has O(1) performance for containsKey, get. Obviously put and remove are not supported.
ImmutableMap objects are constructed by using either the elegant static convenience methods of() and copyOf() or a Builder object.
You can maintain a Map
(for fast lookup) and List
(for order) but a LinkedHashMap
may be the simplest. You can also try a SortedMap
eg TreeMap
, which an have any order you specify.
上一篇: 遍历地图的所有键
下一篇: 实现Map并保持插入顺序的Java类?