我正在学习写一些lambda表示作为 FunctionalInterface 。 所以,要添加我使用的两个整数:
I was learning to write some lambda representation as FunctionalInterface. So, to add two integers I used:
BiFunction<Integer, Integer, Integer> biFunction = (a, b) -> a + b; System.out.println(biFunction.apply(10, 60));给我输出 70 。但是如果我把它写成这个
Gives me the output 70. But if I write it as this
BinaryOperator<Integer, Integer, Integer> binaryOperator = (a, b) -> a + b;我收到错误消息
类型参数的数量错误:3;必填:1
Wrong number of type arguments: 3; required: 1
不是 BinaryOperator BinaryFunction ?我该如何改进?
Isn't BinaryOperator a child of BinaryFunction? How do I improve it?
推荐答案BinaryOperator
由于 BinaryOperator 适用于单一类型的操作数和结果。即 BinaryOperator< T> 。
BinaryOperator不是BinaryFunction的子代吗?
Isn't BinaryOperator a child of BinaryFunction?
是的。 BinaryOperator 扩展BiFunction 。 但是请注意文档状态(格式化我的):
Yes. BinaryOperator does extends BiFunction. But do note the documentation states(formatting mine):
这是 BiFunction 对于 操作数和结果都是相同类型 的情况。
This is a specialization of BiFunction for the case where the operands and the result are all of the same type.
完整的表示形式为:
BinaryOperator<T> extends BiFunction<T,T,T>因此您的代码可以使用
BinaryOperator<Integer> binaryOperator = (a, b) -> a + b; System.out.println(binaryOperator.apply(10, 60));IntBinaryOperator
如果您应该处理当前示例中的两个原始整数(添加我使用的两个整数),则可以使用 IntBinaryOperator FunctionalInterface as
IntBinaryOperator
If you're supposed to be dealing with two primitive integers as currently in your example (add two integers I used), you can make use of the IntBinaryOperator FunctionalInterface as
IntBinaryOperator intBinaryOperator = (a, b) -> a + b; System.out.println(intBinaryOperator.applyAsInt(10, 60));
表示对两个 int的操作 - 操作数值并生成的int值结果。这是 int 的 BinaryOperator 的原始类型专门化。
Represents an operation upon two int-valued operands and producing an int-valued result. This is the primitive type specialization of BinaryOperator for int.
我使用的是Integer,我仍然可以使用IntBinaryOperator
I am using Integer, can I still use IntBinaryOperator
是的,您仍然可以使用它 但 会注意到 IntBinaryOperator
Yes, you can still use it but notice the representation of the 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);首先会产生拆箱 的开销和第二个到基元然后自动装箱总和作为结果的输出类型整数。
would incur you an overhead of unboxing first and second to primitives and then autoboxing the sum as an output to result of type Integer.
注意 :请小心使用 null-safe值作为 Integer ,否则你最终会得到 NullPointerException 。
Note: Be careful of using null-safe values for the Integer though or else you would probably end up with a NullPointerException.
更多推荐
我应该使用哪个FunctionalInterface?
发布评论