您的位置:首页 > 产品设计 > UI/UE

java Map排序(按key和按value)

2011-10-15 13:02 501 查看
转自:http://blog.163.com/mageng11@126/blog/static/140808374201131992320753/

1、按照key排序

对于java中Map的排序,有排序Map,比如TreeMap,对于这个Map,首先只能按照键排序,其次再put和remove的时候由于需要排序,性能上会有所牺牲。

这种方案,使用hashmap进行创建和添加,如果需要按照key排序,则可以将该hashmap作为参数传递到new TreeMap(hashmap),则可以完成按照key的排序

Java代码
TreeMap treemap = new TreeMap(hashmap);

TreeMap treemap = new TreeMap(hashmap);
2、按照value排序

使用hashmap,然后添加比较器,进行排序

Java代码
Collections.sort(hashtmap, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return (o2.getValue() - o1.getValue());
}
});

Collections.sort(hashtmap, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return (o2.getValue() - o1.getValue());
}
});
当然比较器按照个人需求写。这只是简单的key是string,然后按照拼音排序,value是int,按照大小排序。。

如果大家有什么比较好的map的排序方式,期待讨论。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: