我应该使用哪个FunctionalInterface?

Man*_*ani 7 java java-8 functional-interface

我正在学习写一些lambda表示作为FunctionalInterface.所以,要添加我使用的两个整数:

BiFunction<Integer, Integer, Integer> biFunction = (a, b) -> a + b;
System.out.println(biFunction.apply(10, 60));
Run Code Online (Sandbox Code Playgroud)

给我输出70.但如果我这样写的话

BinaryOperator<Integer, Integer, Integer> binaryOperator = (a, b) -> a + b;
Run Code Online (Sandbox Code Playgroud)

我收到一个错误说

错误的类型参数数量:3; 要求:1

不是BinaryOperator孩子BinaryFunction吗?我该如何改进?

Nam*_*man 10

BinaryOperator

因为BinaryOperator可以处理单一类型的操作数和结果.即BinaryOperator<T>.

BinaryOperator不是BinaryFunction的子代吗?

是.BinaryOperator没有extends BiFunction.但请注意文档说明(格式化我的):

BiFunction对于操作数和结果都是相同类型的情况, 这是一种特殊化.

完整的表示如下:

BinaryOperator<T> extends BiFunction<T,T,T>
Run Code Online (Sandbox Code Playgroud)

因此你的代码应该使用

BinaryOperator<Integer> binaryOperator = (a, b) -> a + b;
System.out.println(binaryOperator.apply(10, 60));
Run Code Online (Sandbox Code Playgroud)

IntBinaryOperator

如果你应该在你的例子中处理两个原始整数(添加我使用的两个整数),你可以使用IntBinaryOperatorFunctionalInterface作为

IntBinaryOperator intBinaryOperator = (a, b) -> a + b;
System.out.println(intBinaryOperator.applyAsInt(10, 60));
Run Code Online (Sandbox Code Playgroud)

表示对两个int值操作数的操作并生成一个int值结果.这是for 的原始类型特化 .BinaryOperatorint


我使用Integer,我仍然可以使用IntBinaryOperator

是的,你仍然可以使用它注意到的表示IntBinaryOperator

Integer first = 10;
Integer second = 60;
IntBinaryOperator intBinaryOperator = new IntBinaryOperator() {
    @Override
    public int applyAsInt(int a, int b) {
        return Integer.sum(a, b);
    }
};
Integer result = intBinaryOperator.applyAsInt(first, second); 
Run Code Online (Sandbox Code Playgroud)

会产生拆箱 firstsecond基元的开销,然后将总和作为类型的输出自动装箱.resultInteger

注意:注意尽量使用 null安全值,Integer否则你最终会得到一个NullPointerException.


dav*_*xxx 6

BiFunction<Integer, Integer, Integer> biFunction = (a, b) -> a + b;
Run Code Online (Sandbox Code Playgroud)

可以用.来表示

BinaryOperator<Integer> binaryOperator = (a, b) -> a + b;
Run Code Online (Sandbox Code Playgroud)

但通常你想要执行算术计算int而不是Integer为了避免拆箱计算(Integer to int)和再次装箱以返回结果(int到Integer):

IntBinaryOperator intBinaryOperator = (a, b) -> a + b;
Run Code Online (Sandbox Code Playgroud)

作为旁注,您还可以使用方法引用而不是lambda来计算两个ints 之间的总和.
Integer.sum(int a, int b)是你在找什么:

IntBinaryOperator biFunction = Integer::sum;
Run Code Online (Sandbox Code Playgroud)