views:

565

answers:

2

I have a sorted map and want to reference its ordered objects by their index position. Is this possible? How would I convert a sorted map to an array list while maintaining the ordering, so I can retrieve an object by its index (order). Is this the only way to do it?

Ideally I could have this structure, and would know the index of an object within that strucre and could rertieve it by saying:

    Object nextObj = structure[4] //this structure is originally a sortedMap
//SortedMap<String, Object> sortedMap = new TreeMap<String, Object>();

My issue is that I have a sorted map to work with in the first place. Is there a known way to do this?

Many thanks for suggesting any approaches to this.

+1  A: 

I would use the following structure

List<Pair<String,Object>> mylist;

The object would be always inserted/searched with the help of a custom Comparator and a set of method like lower_bound/upper_bound/equal_bound just like C++ (for example see here for a java implementation)

Pierre
We use this all the time and it is staggeringly quick to find stuff. In addition you can customise it to get a sublist between two keys
Fortyrunner
+1  A: 

You can retrieve a key-value array from your SortedMap by doing

Object[] objects = structure.entrySet().toArray();
Object nextObj = structure[4];

The code below shows how get object's key and value

java.util.Map.Entry<K, V> entry = (java.util.Map.Entry<K, V>) structure[4];
K key = entry.getKey();
V value = entry.getValue();

Edit: sample of getting object value and key

nandokakimoto
entrySet() will return a set of Map.Entry objects. If you need a value, use values(). And yes, iteration over them will keep the sorting order
Dmitry
Is there anyway to know that the set returned by entrySet() will maintain the ordering of the structure it came from?In other words would the array be sorted like the original sortedMap?
denchr
This was answered before my page was refreshed :)
denchr
I am getting a runtime error when trying to cast the Object array taken from the values().toArray(), to the specific object type of the sorted map from which it originally came from. Compile time is fine, but at runtime I get and casting exception: java.lang.Object; cannot be cast to [Lcom.MyType; Any ideas?
denchr
Yes, it's because each array index contais a java.util.Map.Entry. So, you need to use getKey() and getValue() methods.
nandokakimoto
@joel_nc: generics is your friend :)
Dmitry