java – 可以将BiFunction引用传递给期望功能接口的方法吗?

我一直只使用 Java 6,现在正赶上来学习 Java 8中的新功能.我在这里阅读这篇文章
http://www.drdobbs.com/jvm/lambda-expressions-in-java-8/240166764?pgno=2

它说:

The Java API defines several generic functional interfaces in the
java.util.function package. One of the interfaces,BiFunction,describes functions with parameter types T and U and return type
R. You can save our string comparison lambda in a variable of that
type:

BiFunction comp
=(第一,第二) – > Integer.compare(first.length(),second.length());

However,that does not help you with sorting. There
is no Arrays.sort method that wants a BiFunction. If you have used a
functional programming language before,you may find this curIoUs. But
for Java programmers,it’s pretty natural. An interface such as
Comparator has a specific purpose,not just a method with given
parameter and return types. Java 8 retains this flavor. When you want
to do something with lambda expressions,you still want to keep the
purpose of the expression in mind,and have a specific functional
interface for it.

但是,当我看到这个帖子时:
How do you assign a lambda to a variable in Java 8?

那里的问题的答案建议完全按照引用的段落说你做不到的.

那么,文章中的信息是不正确的,还是我在这里读错了?

谢谢!

解决方法

我没有看到链接的SO答案中的任何内容文章相矛盾.

类型系统的常规规则适用于功能接口.

如果将变量声明为BiFunction< String,String,Integer> bifunc,您将无法将其传递给需要Comparator< String>的方法.因为BiFunction< String,Integer>不是Comparator< String>的子类型.

功能类型遵循所有通常规则的事实是允许以最小的扰动添加这个新功能.

如果你想用BiFunction制作一个比较器,你所要做的就是像这样添加:: apply:

BiFunction<String,Integer> bifunc = (a,b) -> 
                               Integer.compare(a.length(),b.length());

Arrays.sort(array,bifunc::apply);

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...