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

6

21

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.

Embonpoint answered 22/6, 2012 at 13:16 Comment(4)
Why do you want to do that? Indices are internal to the TreeMap implementation. You shouldn't use them. You should always rely only on keys(), values() and get(key) methods.Sambar
It's quite deliberate that you cannot do this, except by just iterating through the entrySet in linear time.Guest
I am developing a music application and have to store albumname in key and albumid in value. The situation is like that for me to get both key and value. I can achieve my task by using an extra ArrayList, but I want to implement it simply.Embonpoint
You can use method keySet() to get the list of keys. Then iterate over them to get to one particular one and use get method to retrieve the valueSambar
T
27

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.

Trifacial answered 22/6, 2012 at 13:30 Comment(1)
I create this array just once at start-up , and then keep it as a look up table. Also, here's an example for getting a typed array myMap.keySet().toArray(new Integer[0]); Thanks!Minetta
A
9

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.

Anking answered 24/10, 2013 at 17:8 Comment(0)
C
6

You can copy entry set in an array list and then get desired entry by index:

list=new ArrayList<Map.Entry<K,V>>(treeMap.entrySet());
Map.Entry<K,V>=list.get(index);

But a) copying takes O(N) time and b) when treeMap changes, the list become invalid.

Circumstantial answered 22/6, 2012 at 13:33 Comment(0)
A
2

This might not be the best way but you'll be able to access your key/value at a particular index.

TreeMap<Object, Object> foo = new TreeMap<Object, Object>();
Object key = foo.keySet().toArray(new Object[foo.size()])[YOUR_INDEX];
Object value = foo.get(key);
Aether answered 22/6, 2012 at 13:30 Comment(0)
C
1

This might be helpful

TreeMap< String,Integer > ht=new TreeMap<>();

ht.put("12",1);
ht.put("22",2);
ht.put("32",3);
ht.put("42",4);
for(int i=0;i<ht.size();i++)
{
   System.out.println(new Vector(ht.keySet()).get(i));
   System.out.println(new Vector(ht.values()).get(i));
}
Certifiable answered 25/2, 2017 at 13:47 Comment(0)
S
-2

here is an other option to get the key from a value :

Map<String, String> map = new HashMap<String, String>();
map.put("s1", "s1Val");
map.put("s2", "s2Val");
map.put("s3", "s3Val");

    // ex: "s2Val" -> return "s2"

int index = new ArrayList<String>(map.values()).indexOf("s2Val");
System.out.println(map.keySet().toArray()[index]); // -> return "s2"
Submaxillary answered 6/3, 2014 at 16:38 Comment(1)
unrelated to the question OP asked. Also, Map does not guarantee orderAffirmative

© 2022 - 2024 — McMap. All rights reserved.