简体   繁体   English

使用 lambda 对 Java 中的列表进行排序

[英]Sorting list of list in Java using lambda

I have a list of list elements, now I want to sort that list using lambda expression, but I am getting compilation error:我有一个列表元素列表,现在我想使用 lambda 表达式对该列表进行排序,但出现编译错误:

Here is working code without lambda:这是没有 lambda 的工作代码:

Collections.sort(positions, new Comparator<List<Integer>>() {
    public int compare(List<Integer> ele1, List<Integer> ele2) {
        // some logic here
        return some_number;
    }
});

Now using lamda, I am trying this:现在使用 lamda,我正在尝试这个:

positions.sort((List<Integer> ele1, List<Integer> ele2) -> {

});

But getting this compilation error:但是得到这个编译错误:

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) -> {})

You are missing a return statement in your lambda:您在 lambda 中缺少return语句:

positions.sort((List<Integer> ele1, List<Integer> ele2) -> {
    // logic...
    return some_number;
});

Note, however, that the idiomatic way to sort such a list in Java 8 is with a Comparator#comparing call:但是请注意,在 Java 8 中对此类列表进行排序的惯用方法是使用Comparator#comparing调用:

positions.sort(Comparator.comparing(l -> logic_that_produces_some_comparable));

.sort expects a function that takes in two lists and returns an integer. .sort需要一个接受两个列表并返回一个整数的函数。

The lambda you have provided takes in two lists and returns nothing.您提供的 lambda 接受两个列表并且不返回任何内容。

You need to return a value in your lambda.您需要在 lambda 中返回一个值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM