Find Maximum element from a List of Integers using Stream in Java 8

In this post, we will see how to find maximum element from a List of Integers using Stream in Java 8.


 

1. Convert to IntStream

The idea is to convert the list to IntStream and use max() method provided by IntStream that returns an OptionalInt containing the maximum element of the stream. In order 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. Stream.max()

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 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 elements of the stream using Integer#max() function, 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 reduce() method which performs a reduction on the elements of the stream, 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 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 function 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 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

 
In order to avoid NullPointerException if the given list is null and NoSuchElementException if given list is empty, we can add below code to all above methods in the beginning:

 
 
References:

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

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz