Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Treemap sorting

Tags:

java

treemap

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.

like image 585
omegasbk Avatar asked Aug 15 '26 18:08

omegasbk


2 Answers

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>

like image 99
Andrew Stubbs Avatar answered Aug 18 '26 07:08

Andrew Stubbs


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

like image 22
kulatamicuda Avatar answered Aug 18 '26 07:08

kulatamicuda



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!