javasortingkey-valuetreemap

How to sort treemap with negative values as key


I have a Map which contains +ve and -ve values as key

Map<String,Integer> dr=new TreeMap<String,Integer>();   

So i am putting "-1" when putting the negative values. SInce this is a treemap so the values are stored in sorted manner .After i put the values and print the treemap using this function

for (Map.Entry<String, Integer> entry : dr.entrySet()) {
  System.out.println(entry.getKey() + ": " + entry.getValue());
}

Output

-1: 4
-2: 3
-3: 5
0: 1
1: 2
2: 5
3: 6

Ideally this should be the output, right?

-3: 5
-2: 3
-1: 4
0: 1
1: 2
2: 5
3: 6

How can I achieve this output?


Solution

  • TreeMap sorts using the key. In this case, your key should be Integer, Use Map instead

    Map<Integer,Integer> dr=new TreeMap<Integer,Integer>();   
    

    and baam , the answer comes. :)