Blankman
Blankman

Reputation: 267020

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.

Upvotes: 19

Views: 41709

Answers (4)

inityk
inityk

Reputation: 486

LinkedHashMap is the proper type of data struture that you're looking for! As It extends the HashMap(which allows you to have an element in key/value pair) and maintains a linkedlist(which gives you insertion order) of the entries.

Also check out the following types of maps for more information:

https://docs.oracle.com/javase/8/docs/api/

Go to AbstractMap and check these out

HashMap & TreeMap

HashTable-http://docs.oracle.com/javase/7/docs/api/java/util/Hashtable.html

Upvotes: 0

vcetinick
vcetinick

Reputation: 2017

Seems like you would need to use a list with a name/value object

List<NameValuePair> values = new Arraylist<NameValuePair>();

and then use the list as you would a normal list

class NameValuePair {
   private name;
   private value;

  ... get/set
}

Upvotes: 1

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 236004

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

Upvotes: 24

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272507

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

Upvotes: 7

Related Questions