• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 500
  • Last Modified:

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?
0
perissf
Asked:
perissf
  • 2
1 Solution
 
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
 
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

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now