Java中的IntStream reduce(IntBinaryOperator op)及其示例

IntStream reduce(IntBinaryOperator op) 使用 联想的 累积函数,并返回一个描述缩减值(如果有)的选项。

null

A. 还原操作 折叠 获取一系列输入元素,并将它们组合成一个汇总结果,例如查找一组数字的和或最大值。运算符或函数 op 如果以下条件成立,则为关联:

(a op b) op c == a op (b op c)

这是一个 终端操作 i、 例如,它可能会穿过水流产生结果或副作用。执行终端操作后,流管道被视为已消耗,不能再使用。

语法:

OptionalInt reduce(IntBinaryOperator op)

参数:

  • 可选性: 包含或不包含int值的容器对象。如果存在一个值,isPresent()将返回true,getAsInt()将返回该值。
  • IntBinaryOperator: 对两个int值操作数进行的运算,并产生一个int值结果。
  • 作品: 用于组合两个值的关联、无状态函数。

返回值: 描述缩减值(如有)的选项。

例1:

// Java code for IntStream reduce
// (IntBinaryOperator op)
import java.util.OptionalInt;
import java.util.stream.IntStream;
class GFG {
// Driver code
public static void main(String[] args)
{
// Creating an IntStream
IntStream stream = IntStream.of( 2 , 3 , 4 , 5 , 6 );
// Using OptionalInt (a container object which
// may or may not contain a non-null value)
// Using IntStream reduce(IntBinaryOperator op)
OptionalInt answer = stream.reduce(Integer::sum);
// if the stream is empty, an empty
// OptionalInt is returned.
if (answer.isPresent()) {
System.out.println(answer.getAsInt());
}
else {
System.out.println( "no value" );
}
}
}


输出:

20

例2:

// Java code for IntStream reduce
// (IntBinaryOperator op)
import java.util.OptionalInt;
import java.util.stream.IntStream;
class GFG {
// Driver code
public static void main(String[] args)
{
// Creating an IntStream
IntStream stream = IntStream.of( 2 , 3 , 4 , 5 , 6 );
// Using OptionalInt (a container object which
// may or may not contain a non-null value)
// Using IntStream reduce(IntBinaryOperator op)
OptionalInt answer = stream.reduce((a, b) -> (a * b));
// if the stream is empty, an empty
// OptionalInt is returned.
if (answer.isPresent()) {
System.out.println(answer.getAsInt());
}
else {
System.out.println( "no value" );
}
}
}


输出:

720
© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享