简体   繁体   中英

Treemap sorting

I have this chunk of code:

private final static TreeMap<String, UserNotification> USER_NOTIFICATION_MAP = new TreeMap<String, UserNotification>();

//Filling the map using services

String idString = "1";
Iterator it = USER_NOTIFICATION_MAP.entrySet().iterator();
while (it.hasNext()) 
{
    Map.Entry pairs = (Map.Entry)it.next();
    idString = pairs.getKey().toString();   
    System.out.println(idString);
}   

For map with the following pairs: 2 - UserNotification, 3 - UserNotification, 4 - UserNotification, 5 - UserNotification, 6 - UserNotification, 7 - UserNotification, 8 - UserNotification, 9 - UserNotification, 10 - UserNotification

the output from the code is: 10 2 3 4 5 6 7 8 9

How is that possible, considering the fact that TreeMap sorts all the data by its keys? I suppose that the key with value 10 should be at the end of the list.

The TreeMap is sorting based on it's keys lexicographically (alphabetically), so anything beginning with a 1 comes before anything starting with a 2 etc.

If you want to sort your map numerically , you should be using a TreeMap<Integer, UserNotification>

You are using String comparison not Integer. So "10" is before "2".

That happens because you're using String s in your key set.

Therefore, the Strings are sorted by lexicographical order, hence 10 is before 2 .

Use Integer s (or Long s) to have the intended order.

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