I want something where I can insert key/value pairs, and the order is the order that I insert the items in.
I have seen some posts regarding map's, but it seems I have to write my own comparator for them.
I want the first item I insert to be the first stored, and the 2nd be the 2nd item in the collection ,etc.
Java HashMap class implements the Map interface which allows us to store key and value pair, where keys should be unique.
Every dictionary is an unordered collection of key-value pairs. You can iterate over a dictionary using a for - in loop, decomposing each key-value pair into the elements of a tuple.
A LinkedHashMap enables iterating over the keys (and therefore values) in insertion-order.
Java uses "sorted collection" to mean a collection such as SortedSet, where (unlike List), the order that the iterator traverses the collection is in accordance with a specified Comparator or the natural order of the elements.
Try using a LinkedHashMap
, from the javadocs:
Hash table and linked list implementation of the Map interface, with predictable iteration order 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).
Why not just create a class
to contain a key and a value, and then store them in your favourite List
implementation?
class Pair {
Key k;
Value v;
}
List<Pair> stuff = new ArrayList<Pair>();
Pair p = new Pair();
...
stuff.add(p);
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