denchr
denchr

Reputation: 4262

referencing java objects on a sorted map by index?

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.

Upvotes: 5

Views: 8877

Answers (2)

nandokakimoto
nandokakimoto

Reputation: 1361

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

Upvotes: 7

Pierre
Pierre

Reputation: 35276

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)

Upvotes: 5

Related Questions