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.
HashMap stores items as key/value pairs. Values can be accessed by indexes, known as keys, of a user-defined type.
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.
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.
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.
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With