如何通过 Collections 改进对 Map 值的排序
当我需要根据值对 Map 进行排序时,我经常遇到这种情况。 JDK 中的地图不适用于此目的,我决定不使用 Guava (看起来这个东西是 一个衬垫,但我不太明白)也不是 Apache Commons,所以我这样做。顺便说一句这是一个非常受欢迎的问题,但大多数答案都在某种程度上是错误的。
Map<String, Long> map = new HashMap<String, Long>();
// populate
List<Map.Entry<String, Long>> list = new LinkedList<Map.Entry<String,Long>>();
for (Map.Entry<String, Long> entry : map.entrySet()) {
list.add(entry);
}
Collections.sort(list, new MapComparable());
LinkedHashMap<String, Long> linkedMap = new LinkedHashMap<String, Long>();
for (Map.Entry<String, Long> entry : list) {
linkedMap.put(entry.getKey(), entry.getValue());
}
}
public static class MapComparable implements Comparator<Map.Entry<String, Long>>{
public int compare(Entry<String, Long> e1, Entry<String, Long> e2) {
return (e1.getValue()<e2.getValue() ? -1 : (e1.getValue()==e2.getValue() ? 0 : 1));
}
}
我的问题是,是否有更好的方法从 Collection 获取 EntrySet 或从 Collection 获取 EntrySet ?看起来不太好。
这可靠吗?
I often get into situation when I need to sort a Map on values. Maps are not meant for that in JDK and I decided not to use Guava (seems like this stuff is one liner but I didn't quite get it) nor Apache Commons, so I do it this way. Btw this is a very popular question, but most of the answers are wrong in one way or another.
Map<String, Long> map = new HashMap<String, Long>();
// populate
List<Map.Entry<String, Long>> list = new LinkedList<Map.Entry<String,Long>>();
for (Map.Entry<String, Long> entry : map.entrySet()) {
list.add(entry);
}
Collections.sort(list, new MapComparable());
LinkedHashMap<String, Long> linkedMap = new LinkedHashMap<String, Long>();
for (Map.Entry<String, Long> entry : list) {
linkedMap.put(entry.getKey(), entry.getValue());
}
}
public static class MapComparable implements Comparator<Map.Entry<String, Long>>{
public int compare(Entry<String, Long> e1, Entry<String, Long> e2) {
return (e1.getValue()<e2.getValue() ? -1 : (e1.getValue()==e2.getValue() ? 0 : 1));
}
}
My question is, is there a better way of getting the EntrySet to / from Collection ? It doesn't look good.
And is this reliable ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为对您的方法的一个非常微小的改进是:
换句话说,使用专为排序设计的数据结构进行排序。
作为一般说明,类似的代码
可以缩短为:
每当您处理
Collection
时。我还认为:
更干净。
What I think is a very slight improvement to your method is:
In other words, do the sorting with a datastructure designed for sorting.
As a general note, code like
Can be shortened to:
whenever you're dealing with
Collection
s.Also I think this:
is cleaner.
您可以维护一个双重数据结构,其中一个设置为提供字符串 -> 的
Map
。长转换,另一个作为List
或提供有序转换的类似结构,并具有将两者一起维护的整体结构。You could maintain a dual data structure, one set as a
Map
that provides string -> long conversions, and the other as aList
or similar structure that provides ordered conversions, with an overall structure to maintain both together.