[英]Sorting list of list in Java using lambda
我有一个列表元素列表,现在我想使用 lambda 表达式对该列表进行排序,但出现编译错误:
这是没有 lambda 的工作代码:
Collections.sort(positions, new Comparator<List<Integer>>() {
public int compare(List<Integer> ele1, List<Integer> ele2) {
// some logic here
return some_number;
}
});
现在使用 lamda,我正在尝试这个:
positions.sort((List<Integer> ele1, List<Integer> ele2) -> {
});
但是得到这个编译错误:
The method sort(Comparator<? super List<Integer>>) in the type List<List<Integer>> is not applicable for the arguments ((List<Integer> ele1, List<Integer> ele2) -> {})
您在 lambda 中缺少return
语句:
positions.sort((List<Integer> ele1, List<Integer> ele2) -> {
// logic...
return some_number;
});
但是请注意,在 Java 8 中对此类列表进行排序的惯用方法是使用Comparator#comparing
调用:
positions.sort(Comparator.comparing(l -> logic_that_produces_some_comparable));
.sort
需要一个接受两个列表并返回一个整数的函数。
您提供的 lambda 接受两个列表并且不返回任何内容。
您需要在 lambda 中返回一个值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.