Stream.reduce
方法将 BinaryOperator
作为参数。 BinaryOperator
的函数签名是 (T,T) -> T
。 BigDecimal::min
方法在其方法签名中只有 1 个参数(即 (T) -> T
)。
当我将 BigDecimal::min
传递给 Stream.reduce
方法时,为什么编译器不报错?
示例代码:
List<BigDecimal> bigDecimalList = new ArrayList<>();
bigDecimalList.add(BigDecimal.valueOf(1));
bigDecimalList.add(BigDecimal.valueOf(2));
bigDecimalList.add(BigDecimal.valueOf(3));
BigDecimal minResult = bigDecimalList.stream().reduce(BigDecimal::min).orElse(BigDecimal.ZERO);
谢谢。
最佳答案
这实际上叫做对特定类型的任意对象的实例方法的引用。
编译器将调用实例作为第一个参数,因此它们是等价的:
BinaryOperator<BigDecimal> b = (left, right) -> left.min(right);
BinaryOperator<BigDecimal> b2 = BigDecimal::min;
b2.apply(left, right);
当你有这样的东西时,在我看来,事情会更有趣:
@FunctionalInterface
interface TriFunction<A, B, C, R> {
R apply(A a, B b, C c);
}
和理论课:
class Test {
int x;
int y;
public Test(int x, int y) {
this.x = x;
this.y = y;
}
public Test copy(int n, int m) {
return new Test(m, n);
}
}
然后你可以这样写:
TriFunction<Test, Integer, Integer, Test> f = Test::copy;
TriFunction<Test, Integer, Integer, Test> f2 =
(test, i, j) -> test.copy(i, j);
关于java - BigDecimal#min 方法是否符合 BinaryOperator 的条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43136408/