我有这块代码:

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);
}

对于具有以下对的 map :
2 - 用户通知,
3 - 用户通知,
4 - 用户通知,
5 - 用户通知,
6 - 用户通知,
7 - 用户通知,
8 - 用户通知,
9 - 用户通知,
10 - 用户通知

代码的输出是:
10
2
3
4
5
6
7
8
9

考虑到 TreeMap 按其键对所有数据进行排序这一事实,这怎么可能?我想值为 10 的键应该在列表的末尾。

最佳答案

TreeMap 是根据它的键按字典顺序(按字母顺序)排序的,因此以 1 开头的任何内容都排在以 2 开头的任何内容之前。

如果要按数字对 map 进行排序,则应该使用 TreeMap<Integer, UserNotification>

关于java - 树状图排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25075896/

10-16 12:22
查看更多