Opposite of minimum value in array example, this example will find the greatest value present or max value in an array using java, java 8, guava and apache commons.
Setup
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 greater than the highest value, we will set the highest variable and proceed until we have looped over each element.
Straight up Java
Java 8
Java 8 contains a number of stream reducing operations and the Stream.max operation is all we need to calculate the max value of an array. In the first set of code, we will convert the array to stream then call the Stream.max operation. It will return an OptionalInt describing the max 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.max returning an OptionalInt which shares the same behavior as above. Looking for more than just the max, IntSummaryStatistics example 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.max method which returns the greatest value present in array.
Apache Commons
Apache commons NumberUtils provides additional functionality to java numbers and contains NumberUtils.max which will return the maximum 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 max
part of Mathematical and Aggregate Operators will find the maximum 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.