# previous value in TreeMap

Hi everybody.
Trivial question on TreeMap: how can I get the value corresponding to the key immediately preceding a given key?
###### Who is Participating?

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Commented:
You can't ;-) That's not how a Map works - even a TreeMap. If you want to do that, you need to do make the keys into a List
Author Commented:
but...I was told that the TreeMap had sorted keys...so I thought that with an iterator I could get the previous key and then ask for the corresponding value...
Also, you can assume that the keys are already sorted, since I put them starting from the older and then proceeding with the newer...(keys are Dates).
If this does not work, then I'd need some help in order to:
-get the keys
- sort them
-get the previous key
Thanks mate
Commented:
You could do something like the following:
``````    public static void prev() {
Map<Integer, String> sorted = new TreeMap<Integer, String>();
for(int i = 0;i < 10;i++) {
sorted.put(i, Integer.toString((int)(Math.random() * Integer.MAX_VALUE), 36));
}
System.out.println(sorted);
List<Integer> keys = new ArrayList<Integer>(sorted.keySet());
String val4 = sorted.get(4);
System.out.printf("Value with key 4 is %s\n", val4);
String val3 = sorted.get(keys.get(keys.indexOf(4) - 1));
System.out.printf("Value with key 3 is %s\n", val3);
}
``````

Experts Exchange Solution brought to you by