Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get key and value of a TreeMap at particular index

Tags:

java

treemap

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.

like image 562
Dileep Perla Avatar asked Jun 22 '12 13:06

Dileep Perla


People also ask

How do I find a key in TreeMap?

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.

How do you access values in TreeMap?

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.

Is TreeMap sorted by key or value?

The elements in TreeMap are sorted on the basis of keys.

How do you get the first value from TreeMap?

Use the firstEntry() method in TreeMap to retrieve the first entry.


2 Answers

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.

like image 193
Chandra Avatar answered Oct 11 '22 23:10

Chandra


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.

like image 34
Booyah Johnson Avatar answered Oct 11 '22 23:10

Booyah Johnson