Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 530
denchr Avatar asked Nov 14 '09 22:11

denchr


People also ask

Can you access a HashMap by index?

HashMap stores items as key/value pairs. Values can be accessed by indexes, known as keys, of a user-defined type.

Does map store elements in sorted order in Java?

Objects are stored in sorted, ascending order. But we can also store in descending order by passing a comparator. Let's see how to create a SortedMap object using this class.

Do Treemaps have indexes?

We can get a TreeMap key or TreeMap value using an index in Java by using an Array. The process is divided into three steps: Use the entrySet() method of the TreeMap class to get a Set view of all the entries stored in the TreeMap object.

Can a Java map be sorted?

Since Java 8, we can use the Stream API and lambda expressions to sort the map. All we need is to call the sorted method over the map's stream pipeline.


2 Answers

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

like image 165
nandokakimoto Avatar answered Sep 30 '22 03:09

nandokakimoto


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)

like image 41
Pierre Avatar answered Sep 30 '22 03:09

Pierre