Opposite of finding the minimum value in arraylist and resembling the same behavior as finding the max value in array, this example will find the greatest value present or max value in an ArrayList using java, java 8, guava and apache commons. For our set up data, we randomly choose American Football center's rookie year and created a List of Integers. A comparable example demonstrates how to get the largest value in arraylist using groovy.
Straight up Java
In this snippet we will use core jdk Collections, a class that consists of static methods that operate on collections, to find the max element. Collections.max will return the max element according to the natural ordering of the elements, in this case returning 1988 from CENTERS_ROOKIE_YEAR
This snippet will use java 8 stream reducing technique to find the maximum integer in the array list. Calling stream() method we will convert the list to a stream then mapToInt function to convert the stream to an IntStream, a specialized stream for dealing with primitive ints. Finally calling the max method which will return an OptionalInt describing the max value found or an empty OptionalInt if the stream is empty. Looking for more than just the max, IntSummaryStatistics is a class that calculates all statistics such as average, count, min and sum.
In both of guava's snippets below, we will use the Ordering class which is a fluent Comparator class to call the max method which will return the greatest value according to this orderings.
This snippet will use apache commons ObjectUtils, a class that performs operations on objects, calling the max() method to find the max value in the ArrayList of Integers.