Find Minimum value in a List of Integers in Java 8

In this post, we will see how to find minimum value in a List of Integers in Java 8.


 

1. Convert List to IntStream

The idea is to convert the list to IntStream and use IntStream#min method that returns an OptionalInt having the minimum value of the stream. We can either use orElse or orElseGet or orElseThrow to unwrap an OptionalInt to get hold of real Integer inside.

Download   Run Code

2. Stream.min()

We can also use min() provided by Stream which accepts a Comparator to compare items in the stream against each other and returns an Optional having the minimum value in the stream.

Download   Run Code

 
Now since Integer#compare takes two ints as argument and returns an int value similar to a Comparator#compare, it complies with Comparator functional interface.

Download   Run Code

3. Reduction operation

We can also perform a reduction operation on the values of the stream using Integer#min function, which then returns an Optional describing the minimum value present.

Download   Run Code

There’s an overloaded version of reduce() method that performs a reduction on the values 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 minimum value in the list.

1. Collectors#minBy returns a Collector that produces the minimal value according to a given Comparator.

Download   Run Code

 
2. Collectors#summarizingInt returns a Collector which applies an int-producing mapping function to each input value and returns summary statistics for the resulting values containing statistics such as count, min, max, sum and average.

Download   Run Code

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

Download   Run Code

5. Using Sorting

If we sort the stream in natural order, then the first value in the stream would be the minimum value. This approach is not recommened as it is very inefficient.

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