This example will show how to compute or calculate the sum of all elements in an array using java, java 8 and apache commons techniques.
Setup
Using a standard java technique, we will iterate over the primitive double array using a enhanced for loop. Each iteration will add the element to the total which will result to the sum of all numbers in the array.
Straight up Java
Java 8
Java 8 Streams contains reduce operations which provides an internal implementation of sum that enables a cleaner, more maintainable, and eloquent of way of handling summing all elements in an array than above. If you choose, stream.parallel will enable the internal implementation to choose to perform the reduce operation in parallel. Looking for more than just sum, DoubleSummaryStatistics example is a class that calculates all statistics such as average, count, min max and sum.
Apache Commons
StatUtils, an appache commons class, provides static methods for computing statistics on primitive double arrays. We will call the sum method which will calculate the sum of the values in the input array.
ReactiveX - RXJava
Using the Observable.from
method will convert the List
to an Observable
then emit the items to the sequence. Next, the sumInteger
part of Mathematical and Aggregate Operators will sum all the Integers emitted by the source. In addition to sumInteger
, sumLong
, sumFloat
and sumDouble
exist as well.