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?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

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.

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
perissfAuthor Commented:
but...I was told that the TreeMap had sorted 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
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));
        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);

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.