This post will discuss how to find the maximum element from a list of Integer using stream in Java.

1. Converting to IntStream

The idea is to convert the list to IntStream and use the max() method provided by IntStream that returns an OptionalInt containing the maximum element of the stream. To unwrap an OptionalInt and get a hold of real Integer inside, we can either use orElseThrow or orElse or orElseGet.

Download  Run Code

2. Using Stream.max() method

The idea is to convert the list into a Stream and call Stream#max() that accepts a Comparator to compare items in the stream against each other to find the maximum element, and returns an Optional containing the maximum element in the stream according to the provided Comparator.

Download  Run Code

 
Since Comparator is a functional interface, and Integer.compare() takes two ints as an argument and returns an int value similar to a Comparator#compare(), it complies with that interface.

Download  Run Code

3. Reduction operation

We can also perform a reduction operation on the stream elements using the Integer#max() method, which then returns an Optional describing the reduced value, which will be the maximum value present.

Download  Run Code

We can also use the overloaded version of the reduce() method, which performs a reduction on the stream elements, using the provided identity value and an associative accumulation function, and returns the reduced value.

Download  Run Code

4. Using Collectors

We can also use Collectors to find the maximum element in the list.

1. Collectors#maxBy() returns a Collector that produces the maximal element according to a given Comparator.

Download  Run Code

 
2. Collectors#summarizingInt() returns a Collector, which applies an int-producing mapping method to each input element and returns summary statistics for the resulting values.

The returned IntSummaryStatistics object contains statistics such as count, min, max, sum, and average.

Download  Run Code

 
3. Collectors#reducing() returns a Collector which performs a reduction of its input elements under a specified BinaryOperator and returns an Optional.

Download  Run Code

5. Using Sorting

This is the simplest but most inefficient way. The idea is to sort the stream in the reverse order, then the first element of the stream would be the maximum element.

Download  Run Code

 
To avoid NullPointerException if the given list is null and NoSuchElementException if the given list is empty, we can add the following code to all the above-mentioned methods at the beginning:

That’s all about finding the maximum element from an Integer List using Stream in Java.

 
References:

1. Stream Javadoc SE 8
2. Collectors Javadoc SE 8