【发布时间】:2018-10-03 22:00:49
【问题描述】:
我没有找到需要的信息,所以我决定创建一个新问题。
我有一个小测试应用程序,我想按值对我的地图进行排序。但是我不明白为什么我不能通过以下方式做到这一点:
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
public class Test {
public int test(int [] array) {
Map<Integer, Integer> map = new HashMap<>();
map.put(1,4);
map.put(2,3);
map.put(5,1);
map.put(7,0);
map.put(4,4);
map.put(9,1);
Collections.sort(map.entrySet(), new Comparator<Map.Entry<Integer, Integer>>() {
@Override
public int compare(Map.Entry<Integer, Integer> t, Map.Entry<Integer, Integer> t1) {
return t.getValue().compareTo(t1.getValue());
}
});
for(Map.Entry<Integer, Integer> entry : map.entrySet()){
sum += entry.getValue();
}
return sum;
}
}
和主类:
public class Main {
public static void main(String[] args) {
Test test = new Test();
System.out.println(test.test(arr));
}
}
在这种情况下,此应用应返回 14。但我有这个消息 Collections.sort(...) 部分:
集合中的排序(java.util.List、java.util.Comparator)不能应用于 (java.util.Set>, 匿名的 java.util.Comparator>) 原因:不存在类型变量 T 的实例,因此 Set> 符合 List
但如果我将其更改为 Collections.min(...) 或 Collections.max(...):
Collections.min(map.entrySet(), new Comparator<Map.Entry<Integer, Integer>>() {
@Override
public int compare(Map.Entry<Integer, Integer> t, Map.Entry<Integer, Integer> t1) {
return t.getValue().compareTo(t1.getValue());
}
});
不会有任何问题。
【问题讨论】:
-
Collections.sort接受List。Set不是List。 -
Collections.sort需要一个List,你给它一个Set。错误信息非常清楚。如果要对地图进行排序,请使用TreeMap。 -
由于您需要的只是值的总和,因此您无需在他的情况下对它们进行排序。我认为这不是真正的用例,但是,在您的实际用例中,您应该能够避免必须按值对 Map 进行排序(尤其是您不能这样做)
标签: java dictionary collections comparator anonymous-class