📜  Java中的DoubleAccumulator累积()方法与示例

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

Java中的DoubleAccumulator累积()方法与示例

Java.DoubleAccumulator.accumulate()方法是Java中的一个内置方法,它使用此 DoubleAccumulator 实例中的给定值进行更新。这意味着它将双精度值作为参数并将其添加到调用它的 DoubleAccumulator 实例中。

句法:

public void accumulate(double valueToBeAccumulated)

参数:此方法接受一个强制参数valueToBeAccumulated ,它是要在此 DoubleAccumulator 的当前实例中更新的双精度值。

返回值:此方法不返回任何值。它只是更新了这个 DoubleAccumulator。

下面的程序演示了该函数:

方案一:

// Java program to demonstrate
// the accumulate() method
  
import java.lang.*;
import java.util.concurrent.atomic.DoubleAccumulator;
  
public class GFG {
    public static void main(String args[])
    {
  
        // Create the DoubleAccumulator instance
        DoubleAccumulator num
            = new DoubleAccumulator(Double::sum,
                                    0L);
  
        // Print after accumulator
        System.out.println("Current DoubleAccumulator"
                           + " value is: "
                           + num);
  
        // Update 2 in this instance
        // using accumulate() method
        num.accumulate(2);
  
        // Print after accumulator
        System.out.println("Updated DoubleAccumulator"
                           + " value is: "
                           + num);
    }
}
输出:
Current DoubleAccumulator value is: 0.0
Updated DoubleAccumulator value is: 2.0

方案二:

// Java program to demonstrate
// the accumulate() method
  
import java.lang.*;
import java.util.concurrent.atomic.DoubleAccumulator;
  
public class GFG {
    public static void main(String args[])
    {
  
        // Create the DoubleAccumulator instance
        DoubleAccumulator num
            = new DoubleAccumulator(Double::sum,
                                    0L);
  
        // Print after accumulator
        System.out.println("Current DoubleAccumulator"
                           + " value is: "
                           + num);
  
        // Update 42.2 in this instance
        // using accumulate() method
        num.accumulate(42.2);
  
        // Print after accumulator
        System.out.println("Updated DoubleAccumulator"
                           + " value is: "
                           + num);
    }
}
输出:
Current DoubleAccumulator value is: 0.0
Updated DoubleAccumulator value is: 42.2