Posts

Showing posts from May, 2021

Finding Median by Stream

Image
This small waterfall is one of the many intermediate operations of the stream. Photo taken in Algonquin, ON The Java's DoubleStream class provides a few methods for common statistics including min(), max(), sum(), and average().  For average(), what does it actually mean?  Here is the description in the specification: The average() method returns an OptionalDouble describing the arithmetic mean of elements of the stream, or an empty optional if the stream is empty. While the arithmetic mean method is handy, we likely want a median method for different needs as well.  The DoubleStream class doesn't provide a median() method but the sorted() method.  We can use the sorted() method to assist in finding the median value. Building the Median Function Given each of existing min(), max(), and average() will return an OptionalDouble, having a median() method to return the same type is preferable.  There are different ways to create a median method, and the goal here is ...