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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With