我刚刚开始阅读Java 8概念,而我却发现一些不足以说服我的东西是Interface中缺少compose和identity方法BiFunction。就我从Java 8文档中读取的内容来看,我Bifunction似乎与Functioninterface 相同,期望它需要一个附加参数,因此在这种情况下Bifunction应该具有与Functioninterface相同的所有功能,但事实并非如此。
因此,有人可以帮助我找到省略这些方法的原因吗?
Function.identity()返回Function接受单个参数并返回该参数的。
A BiFunction有两个参数,那么其中一个会identity()返回?
类似地,compose()用于Function通过将第一个的结果Function作为第二个期望的单个参数传递来组成两个s Function。
对于具有两个参数的函数,您将如何实现类似的东西?第一个函数将产生单个值,但是第二个函数需要两个参数。
您仍然可以通过将a的结果作为参数传递给BiFunctiona 。为此,您需要andThen。FunctionBiFunctionFunction
例如,假设您具有BiFunction<Integer,Integer,Integer>以下内容:
BiFunction<Integer,Integer,Integer> mul = (x,y) -> x*y;
Run Code Online (Sandbox Code Playgroud)
并且您有一个Function<Integer,Integer>:
Function<Integer,Integer> plus5 = x -> x + 5;
Run Code Online (Sandbox Code Playgroud)
您可以andThen按如下方式编写它们:
BiFunction<Integer,Integer,Integer> mulPlus5 = mul.andThen(plus5);
Run Code Online (Sandbox Code Playgroud)
并称之为:
int result = mulPlus5.apply(2,3); // this will multiply 2*3 and add 5, resulting in 11.
Run Code Online (Sandbox Code Playgroud)
您不能先应用plus5(或使用某些BiFunction替代方法),然后再将其结果传递给mul,因为它带有mul2个参数,而应用plus5(或任何其他Function或BiFunction)将导致单个值。
| 归档时间: |
|
| 查看次数: |
63 次 |
| 最近记录: |