📜  Java中的 LongStream reduce(LongBinaryOperator op)

📅  最后修改于: 2022-05-13 01:55:39.173000             🧑  作者: Mango

Java中的 LongStream reduce(LongBinaryOperator op)

LongStream reduce(LongBinaryOperator op)使用关联累加函数对此流的元素执行归约,并返回描述归约值的 OptionalLong(如果有)。

归约操作折叠采用一系列输入元素并将它们组合成一个汇总结果,例如找到一组数字的总和或最大值。如果满足以下条件,则运算运算符或函数op是关联的:

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

这是一个终端操作,即它可以遍历流以产生结果或副作用。终端操作完成后,流管道被视为消耗,不能再使用。

句法 :

OptionalLong reduce(LongBinaryOperator op)

参数 :

  • OptionalLong :一个容器对象,可能包含也可能不包含 long 值。如果存在值,isPresent() 将返回 true,而 getAsLong() 将返回该值。
  • LongBinaryOperator :对两个长值操作数的操作并产生一个长值结果。
  • op :用于组合两个值的关联无状态函数。

返回值:一个 OptionalLong 描述减少的值,如果有的话。

示例 1:

// Java code for LongStream reduce
// (LongBinaryOperator op)
import java.util.OptionalLong;
import java.util.stream.LongStream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
        // Creating a LongStream
        LongStream stream = LongStream.of(9L, 10L, 11L, 12L);
  
        // Using OptionalLong (a container object which
        // may or may not contain a non-null value)
        // Using LongStream reduce(LongBinaryOperator op)
        OptionalLong answer = stream.reduce(Long::sum);
  
        // if the stream is empty, an empty
        // OptionalLong is returned.
        if (answer.isPresent()) {
            System.out.println(answer.getAsLong());
        }
        else {
            System.out.println("no value");
        }
    }
}

输出 :

42

示例 2:

// Java code for LongStream reduce
// (LongBinaryOperator op)
import java.util.OptionalLong;
import java.util.stream.LongStream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
        // Creating a LongStream
        LongStream stream = LongStream.of(9L, 10L, 11L, 12L);
  
        // Using OptionalLong (a container object which
        // may or may not contain a non-null value)
        // Using LongStream reduce(LongBinaryOperator op)
        OptionalLong answer = stream.reduce((a, b) -> 2 * (a * b));
  
        // if the stream is empty, an empty
        // OptionalLong is returned.
        if (answer.isPresent()) {
            System.out.println(answer.getAsLong());
        }
        else {
            System.out.println("no value");
        }
    }
}

输出 :

95040