Java 使用匿名类比较器进行Collection.sort
我没有找到需要的信息,所以我决定提出一个新问题 我有一个小测试应用程序,我想按值对地图进行排序。但我不明白为什么我不能用下面的方法来做:Java 使用匿名类比较器进行Collection.sort,java,dictionary,collections,comparator,anonymous-class,Java,Dictionary,Collections,Comparator,Anonymous Class,我没有找到需要的信息,所以我决定提出一个新问题 我有一个小测试应用程序,我想按值对地图进行排序。但我不明白为什么我不能用下面的方法来做: import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Map; public class Test { public int test(int [] array
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;
}
}
在这种情况下,此应用程序应返回14。但我有这个留言
集合。排序(…)部分:
集合中的排序(java.util.List、java.util.Comparator)不能应用于
(java.util.Set>,
匿名的
java.util.Comparator>)
原因:不存在类型变量T的实例,因此
集合>符合列表
但如果我将其更改为Collections.min(…)或Collections.max(…):
Collections.min(map.entrySet(),new Comparator()){
@凌驾
公共int比较(Map.Entry t,Map.Entry t1){
返回t.getValue().compareTo(t1.getValue());
}
});
不会有问题。Java映射无法按值排序。但是您可以从
Map.entrySet()
创建一个列表,或者您根本不需要集合
使用列表和比较器
List<Map.Entry<Integer, Integer>> list = new ArrayList<>(map.entrySet());
list.sort(Comparator.comparing(Map.Entry::getValue));
Collections.sort
接受列表
。集合
不是列表
集合。排序
获取一个列表
,您给它一个集合
。错误信息非常清楚。如果要对映射进行排序,请使用TreeMap
。因为您只需要值的总和,所以不需要在这种情况下对它们进行排序。我假设这不是真实的用例,但是,在您的真实用例中,您应该能够避免按值对映射进行排序(尤其是因为您不能这样做)
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());
}
});
List<Map.Entry<Integer, Integer>> list = new ArrayList<>(map.entrySet());
list.sort(Comparator.comparing(Map.Entry::getValue));
map.entrySet().stream()
.sorted(Comparator.comparing(Map.Entry::getValue))
//do something here