Is there an simple way or a function that can get the difference, product or quotient of all numbers in an array

RayNature :

So I just want to know if there's a simpler way to get all the numbers in an array and subtract, add, multiply, and divide them better than what I have done here: (the code here is to subtract all the numbers in an array)

 double diff = numArray[0];
 for (int i=1; i!=numArray.length; i++) {
    diff -= numArray[i];
 }

or is there a function that can make my life easier, because I know there is a function to add all the numbers in an array but wasn't able to find anything else.

MC Emperor :

Cleaner? Your code is pretty clean I think.

However, an alternative may be using streams:

double[] numArray = { 17.0, 13.0, 36.5, 7.5, 3.2 };
double result = DoubleStream.of(numArray)
    .skip(1)
    .reduce(numArray[0], (a, b) -> a - b);
System.out.println(result);

What happens here? We use the Stream specialization for primitive doubles, DoubleStream, in order to walk over the elements of the double array. We skip the first element, because all subsequent elements should be subtracted from the first element. Then we perform a reduction operation, with as initial value the first element of the array, and we subtract the subsequent element from the previous result.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=195217&siteId=1