[英]Sort treemap on value and return it as treemap agin.
i have treemap and i sort it on value with code bellow. 我有树状图,我用下面的代码对它进行排序。 how can i get results as treemap again?
我怎样才能再次获得树状图的结果?
static <K, V extends Comparable<? super V>> SortedSet<Map.Entry<K, V>> entriesSortedByValues(
Map<K, V> map) {
SortedSet<Map.Entry<K, V>> sortedEntries = new TreeSet<Map.Entry<K, V>>(
new Comparator<Map.Entry<K, V>>() {
@Override
public int compare(Map.Entry<K, V> e1, Map.Entry<K, V> e2) {
int res = e1.getValue().compareTo(e2.getValue());
return res != 0 ? res : 1;
}
});
sortedEntries.addAll(map.entrySet());
return sortedEntries;
}
You're creating a TreeSet
, whereas, you need to create a TreeMap
. 您正在创建一个
TreeSet
,而您需要创建一个TreeMap
。 The comparator which you pass to TreeMap
, will use the map
passed as parameter, to fetch the value and compare them. 传递给
TreeMap
的比较器将使用作为参数传递的map
来获取值并进行比较。
Change your method to: 将您的方法更改为:
static <K, V extends Comparable<? super V>> TreeMap<K, V> entriesSortedByValues(final Map<K, V> map) {
TreeMap<K, V> sortedEntries = new TreeMap<K, V>(new Comparator<K>() {
@Override
public int compare(K o1, K o2) {
return map.get(o1).compareTo(map.get(o2));
}
});
sortedEntries.putAll(map);
return sortedEntries;
}
Tested with: 经过测试:
public static void main(String args[]) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(1, 3);
map.put(3, 1);
map.put(5, 6);
map.put(2, 10);
// Prints: {3=1, 1=3, 5=6, 2=10}
System.out.println(entriesSortedByValues(map));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.