简体   繁体   English

BiFunction 的区别<X, X>和 BinaryOperator<X>

[英]Difference between BiFunction<X, X> and BinaryOperator<X>

I am not able to understand that how come BinaryOperator<Integer> could be placed at the place of A in the code below, but not BiFunction<Integer, Integer> ?我无法理解为什么BinaryOperator<Integer>可以放在下面代码中的A位置,而不是BiFunction<Integer, Integer>

A foo = (a, b) -> { return a * a + b * b; };
int bar = foo.apply(2, 3);
System.out.println(bar);

Could someone please help me understand it.有人可以帮助我理解它。

BinaryOperator is a special BiFunction . BinaryOperator是一个特殊的BiFunction So you can assign the same expression to both of them.因此,您可以为它们分配相同的表达式。 Check this out.看一下这个。

BinaryOperator<Integer> foo = (a, b) -> {
    return a * a + b * b;
};
BiFunction<Integer, Integer, Integer> barFn = (a, b) -> {
    return a * a + b * b;
};

If you look at the source code, it would be如果你查看源代码,它会是

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

The Bifunction and the BinaryOperator are same but the only difference here is the argument type and the return type of interfaces. Bifunction 和 BinaryOperator 是相同的,但这里唯一的区别是接口的参数类型和返回类型。

Consider a case where you want to concatenate two strings and return the result.考虑一种您想要连接两个字符串并返回结果的情况。 In this case, you can choose either one of them but BinaryOperator is a good choice to go with because if you focus on the arguments and the return type, they all are the same.在这种情况下,您可以选择其中之一,但 BinaryOperator 是一个不错的选择,因为如果您关注参数和返回类型,它们都是相同的。

BinaryOperator<String> c=(str,str1)->str+str1;

you can do the same with Bifunction but now see the difference here:你可以用 Bifunction 做同样的事情,但现在在这里看到不同之处:

BiFunction<String,String,String> c=(str,str1)->str+str1;

Now consider a case in which we want to add two integers and return a string.现在考虑我们想要将两个整数相加并返回一个字符串的情况。 Here we can only choose the BiFunction and not the BinaryOperator:这里我们只能选择 BiFunction 而不是 BinaryOperator:

BiFunction<Integer,Integer,String> c=(a,b)->"Answer="+(a+b);

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

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