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


Java DoubleStream reduce(double identity, DoubleBinaryOperator op)用法及代码示例


DoubleStream reduce(double identity,DoubleBinaryOperator op)使用提供的标识值和关联的累加函数对此流的元素执行精简,然后返回精简的值。

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

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

这是终端操作,即可能会遍历流以产生结果或副作用。执行终端操作后,流管线被视为已消耗,无法再使用。


用法:

double reduce(double identity,  DoubleBinaryOperator op)

参数:

  • identity:累加函数的标识值。
  • DoubleBinaryOperator:对两个双值操作数进行运算并产生双值结果。
  • op:用于组合两个值的关联无状态函数。

返回值:减少的结果。

范例1:

// Java code for DoubleStream reduce 
// (double identity, DoubleBinaryOperator op) 
import java.util.*; 
import java.util.stream.DoubleStream; 
  
class GFG { 
  
    // Driver code 
    public static void main(String[] args) 
    { 
        // Creating a DoubleStream 
        DoubleStream stream = DoubleStream.of(1.2, 2.3, 
                                              3.4, 4.5, 5.6); 
  
        // Using DoubleStream reduce 
        // (double identity, DoubleBinaryOperator op) 
        double answer = stream.reduce(5, (num1, num2) 
                                             -> (num1 + num2)); 
  
        // Displaying the result 
        System.out.println(answer); 
    } 
}

输出:

22.0

范例2:

// Java code for DoubleStream reduce 
// (double identity, DoubleBinaryOperator op) 
import java.util.*; 
import java.util.stream.DoubleStream; 
  
class GFG { 
  
    // Driver code 
    public static void main(String[] args) 
    { 
        // Creating a DoubleStream 
        DoubleStream stream = DoubleStream.of(2.1, 3.2, 
                                              4.3, 5.4, 6.5); 
  
        // Using DoubleStream reduce 
        // (double identity, DoubleBinaryOperator op) 
        double answer = stream.reduce(3, (num1, num2) 
                                             -> (num1 * num2) * 2); 
  
        // Displaying the result 
        System.out.println(answer); 
    } 
}

输出:

97367.96160000002


相关用法


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