当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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:对两个long值操作数进行运算并产生long值结果。
  • 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


相关用法


注:本文由纯净天空筛选整理自Sahil_Bansall大神的英文原创作品 LongStream reduce(LongBinaryOperator op) in Java。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。