微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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);

原文地址:https://www.jb51.cc/java/127987.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐