繁体   English   中英

我应该使用哪个FunctionalInterface?

[英]Which FunctionalInterface should I use?

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

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

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

BinaryOperator<Integer, Integer, Integer> binaryOperator = (a, b) -> a + b;

我收到一个错误说

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

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

BinaryOperator

由于BinaryOperator处理单一类型的操作数和结果 BinaryOperator<T>

BinaryOperator不是BinaryFunction的子代吗?

是。 BinaryOperator确实extends BiFunction 但请注意文档说明(格式化我的):

这是BiFunction适用于操作数和结果都是相同类型的情况

完整的表示如下:

BinaryOperator<T> extends BiFunction<T,T,T>

因此你的代码应该使用

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

IntBinaryOperator

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

IntBinaryOperator intBinaryOperator = (a, b) -> a + b;
System.out.println(intBinaryOperator.applyAsInt(10, 60));

表示对两个int值的操作数进行的操作,并生成一个int值结果。 这是用于intBinaryOperator原始类型 BinaryOperator


我使用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); 

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

注意 :注意尽量使用Integer null安全值 ,否则你最终可能会遇到NullPointerException

BiFunction<Integer, Integer, Integer> biFunction = (a, b) -> a + b;

可以用。来表示

BinaryOperator<Integer> binaryOperator = (a, b) -> a + b;

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

IntBinaryOperator intBinaryOperator = (a, b) -> a + b;

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

IntBinaryOperator biFunction = Integer::sum;

BinaryOperator不是BinaryFunction的子代吗?

是的。 如果你看一下BinaryOperator源代码,你会看到:

public interface BinaryOperator<T> extends BiFunction<T,T,T> {
    // ...
}

所以你只需要修复你的语法:

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

我该如何改进?

您可以使用IntBinaryOperator 它甚至可以简化sytax:

IntBinaryOperator binaryOperator = (a, b) -> a + b;
System.out.println(binaryOperator.applyAsInt(10, 60));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM