繁体   English   中英

树图排序

[英]Treemap sorting

我有这段代码:

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

对于具有以下对的地图:2 - UserNotification,3 - UserNotification,4 - UserNotification,5 - UserNotification,6 - UserNotification,7 - UserNotification,8 - UserNotification,9 - UserNotification,10 - UserNotification

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

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

TreeMap字典顺序 (按字母顺序)对其键进行排序,因此以1开头的任何内容都以2开头的任何内容开头。

如果要以数字方式对地图进行排序,则应使用TreeMap<Integer, UserNotification>

您正在使用字符串比较而不是整数。 所以“10”在“2”之前。

这是因为您在密钥集中使用了String

因此, Strings按字典顺序排序,因此102之前。

使用Integer (或Long Integer )来获得预期的顺序。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM