omegasbk
omegasbk

Reputation: 906

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.

Upvotes: 3

Views: 1077

Answers (3)

Mena
Mena

Reputation: 48404

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

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

Use Integers (or Longs) to have the intended order.

Upvotes: 3

kulatamicuda
kulatamicuda

Reputation: 1651

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

Upvotes: 3

Andrew Stubbs
Andrew Stubbs

Reputation: 4462

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>

Upvotes: 5

Related Questions