简体   繁体   中英

How to sort treemap with -ve 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 acheive this output?

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. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM