Similar to finding the average of an arraylist or collection, this example will use java, java 8, guava and apache commons to demonstrate how to find the average or the arithmetic mean of a numeric array of a primitive type.
Straight up Java
Using an imperative programming style, we will iterate over the numbers array using a for each loop. Each iteration will add to the total and then divide by the array length, thus finding the average.
In java 8, the JDK provides a series of reduction operations which provides an internal implementation. Unlike the example above, this abstraction enables a cleaner, more maintainable, and eloquent of way of handling finding the average of the array. If you choose, stream.parallel will enable the internal implementation to choose to perform the reduce operation in parallel. Looking for more than just the average, DoubleSummaryStatistics is a class that calculates all statistics such as average, count, min max and sum.
Guava provides a class for arithmetic on doubles that is not covered by java.lang.Math.
Apache commons Mean class will computes the arithmetic mean of a set of double values.
ReactiveX - RXJava
Observable.from method will convert the
List to an
Observable so it will emit the items to the sequence. Next, the
averageInteger part of Mathematical and Aggregate Operators will compute the average of sequence returning a single item.