I have a TreeMap with a set of 'Key and Value' pairs. How can I get both Key and Value at a particular Index of the TreeMap?
EDIT : @TO-ALL : Thanks. But I know how to implement it by using an extra ArrayList. I just thought is there any way to achieve this without using an extra ArrayList.
TreeMap containsKey() Method in Java containsKey() method is used to check whether a particular key is being mapped in the TreeMap or not. It takes the key element as a parameter and returns True if that element is mapped in the map.
util. TreeMap. get() method of TreeMap class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key.
The elements in TreeMap are sorted on the basis of keys.
Use the firstEntry() method in TreeMap to retrieve the first entry.
If you really want to use TreeMap and get by position, you can use the following:
key => treemap.keySet().toArray()[0]
value => treemap.get(key);
OR (if you just want value)
treemap.values().toArray()[0];
But I would suggest you use iterator, as in the above method, it needs to create array whenever you want to find (so not so efficient) and also you should be careful enough to make sure index don't go out of reach.
First off, I'm not sure why people here so frequently concern themselves about the validity of a question. There are numerous instances where people have seen fit to maintain an ArrayList in sorted order. Maintaining an ArrayList in sorted order is grossly inefficient for large lists.
The Entry nodes of the standard Java (Oracle) source distribution do not maintain the size of their descendant trees. Because of this, it is not possible to identify an element within the map by index without an inefficient sequential search.
I find this drawback so severe that I have written my own AVL map that can efficiently get elements by index and compute indexOf(E). Making this possible is as simple as maintaining the sizes each of the left and right branches of an Entry. There is some chance that the Glazedlists library has a searchable tree embedded it in somewhere. You may wish to review that.
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