树状图按值排序我想要写一个比较器,它允许我按值对树状图进行排序,而不是默认的自然排序。我试过这样做,但找不出哪里出了问题:import java.util.*;class treeMap {
public static void main(String[] args) {
System.out.println("the main");
byValue cmp = new byValue();
Map<String, Integer> map = new TreeMap<String, Integer>(cmp);
map.put("de",10);
map.put("ab", 20);
map.put("a",5);
for (Map.Entry<String,Integer> pair: map.entrySet()) {
System.out.println(pair.getKey()+":"+pair.getValue());
}
}}class byValue implements Comparator<Map.Entry<String,Integer>> {
public int compare(Map.Entry<String,Integer> e1, Map.Entry<String,Integer> e2) {
if (e1.getValue() < e2.getValue()){
return 1;
} else if (e1.getValue() == e2.getValue()) {
return 0;
} else {
return -1;
}
}}我想我要问的是:我能得到一个Map.Entry传递给比较国?
3 回答
慕虎7371278
TA贡献1802条经验 获得超4个赞
LinkedHashMap<Integer, String> sortedMap = map.entrySet().stream(). sorted(Entry.comparingByValue()). collect(Collectors.toMap(Entry::getKey, Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
有只小跳蛙
TA贡献1824条经验 获得超8个赞
TreeMapSortedMap
A
Map这进一步提供了一个 全序关于它 钥匙.
Map.entrySet()
SortedSetMap.EntryMapComparable:
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;} Map<String,Integer> map = new TreeMap<String,Integer>();
map.put("A", 3);
map.put("B", 2);
map.put("C", 1);
System.out.println(map);
// prints "{A=3, B=2, C=1}"
System.out.println(entriesSortedByValues(map));
// prints "[C=1, B=2, A=3]"SortedSetMap.EntryentrySet()
注: ==为 Integer
Integer====Integer
System.out.println(new Integer(0) == new Integer(0)); // prints "false"!!!
相关问题
添加回答
举报
0/150
提交
取消
