views:

4254

answers:

5
+8  Q: 

Java Ordered Map

In Java, Is there an object that acts like a Map for storing and accessing key/value pairs, but can return an ordered list of keys and an ordered list of values, such that the key and value lists are in the same order?

So as explanation-by-code, I'm looking for something that behaves like my fictitious OrderedMap:

OrderedMap om = new OrderedMap();
om.put(0, "Zero");
om.put(7, "Seven");

Object o = om.get(7); // o is "Seven"
List keys = om.getKeys();
List values = om.getValues();

for(int i = 0; i < keys.size(); i++)
{
    Object key = keys.get(i);
    Object value = values.get(i);
    Assert(om.get(key) == value);
}
+5  A: 

Is there an object that acts like a Map for storing and accessing key/value pairs, but can return an ordered list of keys and an ordered list of values, such that the key and value lists are in the same order?

You're looking for java.util.LinkedHashMap. You'll get a list of Map.Entry<K,V> pairs, which always get iterated in the same order. That order is the same as the order by which you put the items in. Alternatively, use the java.util.SortedMap, where the keys must either have a natural ordering or have it specified by a Comparator.

John Feminella
+3  A: 

I think the closest collection you'll get from the framework is the SortedMap

bruno conde
I'd love to know about the down vote ...
bruno conde
+18  A: 

The SortedMap interface (with the implementation TreeMap) should be your friend.

The interface has the methods:

  • keySet() which returns a set of the keys in ascending order
  • values() which returns a collection of all values in the ascending order of the corresponding keys

So this interface fulfills exactly your requirements. However, the keys must have a meaningful order. Otherwise you can used the LinkedHashMap where the order is determined by the insertion order.

dmeister
+1  A: 

SortedMap

Ichorus
+1  A: 

I think the SortedMap interface enforces what you ask for and TreeMap implements that.

http://java.sun.com/j2se/1.5.0/docs/api/java/util/SortedMap.html http://java.sun.com/j2se/1.5.0/docs/api/java/util/TreeMap.html

CJ