DoubleAccumulator
Comprehensive guide to working with DoubleAccumulator class.
We'll cover the following
If you are interviewing, consider buying our number#1 course for Java Multithreading Interviews.
Overview
The DoubleAccumulator
class is similar to the DoubleAdder
class, except that the DoubleAccumulator
class allows for a function to be supplied that contains the logic for computing results for accumulation. In contrast to DoubleAdder
, we can perform a variety of mathematical operations rather than just addition. The supplied function to a DoubleAccumulator
is of type DoubleBinaryOperator
. The class DoubleAccumulator
extends from the class Number
but doesn’t define the methods compareTo()
, equals()
, or hashCode()
and instances of the class shouldn’t be used as keys in collections such as maps.
An example of creating an accumulator that simply adds double values presented to it appears below:
// function that will be supplied to an instance of DoubleAccumulator
DoubleBinaryOperator doubleBinaryOperator = new DoubleBinaryOperator() {
@Override
public double applyAsDouble(double left, double right) {
return left + right;
}
};
// instantiating an instance of DoubleAccumulator with an initial value of zero
DoubleAccumulator longAccumulator = new DoubleAccumulator(doubleBinaryOperator, 0);
Note that in the above example, we have supplied a function that simply adds the new double value presented to it. The method applyAsDouble
has two operands left
and right
. The left
operand is the current value of the DoubleAccumulator
. In the above example, it’ll be zero initially, because that is what we are passing-in to the constructor of the DoubleAccumulator
instance. The code widget below runs this example and prints the operands and the final sum.
Create a free account to view this lesson.
Continue your learning journey with a 14-day free trial.
By signing up, you agree to Educative's Terms of Service and Privacy Policy