Opposite of maximum value in array example, this example will find the lowest or minimum value in array using java, java 8, guava and apache commons.
Setup
Straight up Java
With straight up java we use a for loop to iterate over an array of numbers comparing each value to the previous. If the value is less than the lowest value, we will set the lowest variable and proceed until we have looped over each element.
Java 8
Java 8 contains a number of stream reduction operations and the Stream.min operation is what we need to find the min value of an array. In the first set of code, we will transform the array to stream then call the Stream.min operation. It will return an OptionalInt describing the min value found or an empty OptionalInt if the stream is empty. The second code snippet will use IntStream, a specialized stream for dealing with primitive ints, calling the IntStream.min returning an OptionalInt which shares the same behavior as above. Looking for more than just the min, IntSummaryStatistics is a class that calculates all statistics such as average, count, min max and sum.
Google Guava
Guava's Ints class specialized in dealing with int primitives contains a Ints.min method which returns the lowest value present in array.
Apache Commons
Apache commons NumberUtils provides additional functionality to java numbers and contains NumberUtils.min which will return the minimum value in the passed in array.
ReactiveX - RXJava
Using the Observable.from
method will convert the List
to an Observable
so it will emit the items to the sequence. Next, the min
, part of Mathematical and Aggregate Operators, will find the minimum numeric value of the source returning a single item. If there is more than one item with the same value, the last one in the sequence will be returned.