Similar to finding the average of a numeric array, this example will compute the arithmetic mean of the values in an arraylist using java, java 8, guava and apache commons. In a comparable example we demonstrate how to find the average of a list of numbers in groovy.
Straight up Java
Using straight up java, we will iterate over the numbers list using an enhanced for each loop. Each iteration will add to the value to the sum variable then divide by the total number of elements in the list.
Using java 8, we will convert the list to a stream then call mapToDouble. The mapToDouble will extract all the values and return a DoubleStream as the result. We will then call the average method defined on the DoubleStream interface to calculate the average of all numbers in the list. The DoubleStream also supports other statistical methods such as max(), min(), average(), count() and sum() and Double Summary Statistics is a state object for collecting them all. The average method will return a OptionalDouble describing the sum of the elements, or an empty optional if the stream is empty.
DoubleMath is a class implemented by google guava that covers arithmetic that isn't covered by java.lang.Math. In the snippet below, we will call DoubleMath.mean which will return the arithmetic mean of the provided list.
Mean, a class supported by apache commons, is a class that calculates the average of a set of values. We will call Mean.evaluate which return the mean of the elements contained in the arraylist.
ReactiveX - RXJava
NUMBERSFORAVERAGE constant to
Observable.from will create a emit the items to the sequence. Next, the
averageDouble is part of Mathematical and Aggregate Operators will find the average numeric value of the source returning a single item. Then using java 8 instance method reference will print out the average result.
averageFloat exists if you are working with other data types.