3

Possible Duplicate:
Bi-directional Map in Java?

How can I retrieve key of Map by index when keys are not numeric and unordered ?

For example :

Map<String, Integer> test = new TreeMap<String, Integer>();
test.put("a", 1);
test.put("b", 2);
test.put("z", 3);
test.put("m", 4);

I want to get z if I have index 2 or a if I have index 0.

I know I can do dirty loop with increment to get it but is there another smart way to do it ?

Community
  • 1
  • 1
Olivier J.
  • 3,115
  • 11
  • 48
  • 71

1 Answers1

1

What makes this a bit confusing is whether you're referring to the index based on the order the item is added, or based on the natural ordering of the key (eg: alphabetical)

You can obtain the list of may keys using map.keySet() but there's no guarantee the key set will be in the order which you add it in

You can use TreeMap instead of HashMap if you want to keep your data in some kind of ordering (eg: alphabetical ordering). If you prefer other way of ordering you can implement your own comparator

gerrytan
  • 40,313
  • 9
  • 84
  • 99
  • yes sorry, I have made mistake, it is well TreeMap not HashMap. I have made an edit on my post. Nivas suggest me a link and there is a good way to do what I am looking for. I will use it unless someone provide me another better solution. – Olivier J. Dec 20 '12 at 23:57