从 Java 中的函数返回比较器
Returning a Comparator from a Function in Java
是否可以从 Java 中的 java.util.function.Function
return 变成 Comparator
?
我在下面的(设计的)示例中尝试了这个,但是 Eclipse 告诉我存在语法错误(“令牌“amountOfPages 上的语法错误”,删除此令牌 ):
import java.util.Comparator;
import java.util.List;
import java.util.function.Function;
public class App
{
private record Book(Integer nrOfPages) {};
static Function<Integer, Comparator<Book>> byHasExactAmountOfPages = Integer amountOfPages -> (Book book1, Book book2) ->
{
if(book1.nrOfPages.equals(amountOfPages) && book2.nrOfPages.equals(amountOfPages))
{
return 0;
}
else if(!book1.nrOfPages.equals(amountOfPages) && !book2.nrOfPages.equals(amountOfPages))
{
return 0;
}
else if(book1.nrOfPages.equals(amountOfPages) && !book2.nrOfPages.equals(amountOfPages))
{
return -1;
}
else
{
return 1;
}
};
public static void main(String[] args)
{
List.of(new Book(1), new Book(2), new Book(3)).stream()
.sorted(byHasExactAmountOfPages.apply(2))
.forEach(System.out::print);
}
}
你错过了参数周围的括号:
here and here
( Integer amountOfPages ) -> (Book book1, Book book2) -> ...
是否可以从 Java 中的 java.util.function.Function
return 变成 Comparator
?
我在下面的(设计的)示例中尝试了这个,但是 Eclipse 告诉我存在语法错误(“令牌“amountOfPages 上的语法错误”,删除此令牌 ):
import java.util.Comparator;
import java.util.List;
import java.util.function.Function;
public class App
{
private record Book(Integer nrOfPages) {};
static Function<Integer, Comparator<Book>> byHasExactAmountOfPages = Integer amountOfPages -> (Book book1, Book book2) ->
{
if(book1.nrOfPages.equals(amountOfPages) && book2.nrOfPages.equals(amountOfPages))
{
return 0;
}
else if(!book1.nrOfPages.equals(amountOfPages) && !book2.nrOfPages.equals(amountOfPages))
{
return 0;
}
else if(book1.nrOfPages.equals(amountOfPages) && !book2.nrOfPages.equals(amountOfPages))
{
return -1;
}
else
{
return 1;
}
};
public static void main(String[] args)
{
List.of(new Book(1), new Book(2), new Book(3)).stream()
.sorted(byHasExactAmountOfPages.apply(2))
.forEach(System.out::print);
}
}
你错过了参数周围的括号:
here and here
( Integer amountOfPages ) -> (Book book1, Book book2) -> ...