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?
perissfAsked:
Who is Participating?
 
CEHJCommented:
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);
    }

Open in new window

0
 
CEHJCommented:
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
0
 
perissfAuthor 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
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.