Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java collection that has key/value pair, and is ordered according to insert order

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.

like image 257
Blankman Avatar asked Nov 29 '11 02:11

Blankman


People also ask

Which collection has key-value pair in Java?

Java HashMap class implements the Map interface which allows us to store key and value pair, where keys should be unique.

Which type of collection contains key-value pairs?

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.

Which of the following is the right choice if the collection has key-value pairs and the order of insertion is to be preserved?

A LinkedHashMap enables iterating over the keys (and therefore values) in insertion-order.

Which collection is ordered in Java?

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.


2 Answers

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).

like image 51
Óscar López Avatar answered Sep 28 '22 04:09

Óscar López


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);
like image 33
Oliver Charlesworth Avatar answered Sep 28 '22 03:09

Oliver Charlesworth