|
我一直只使用
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); (编辑:安卓应用网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|