Java Streams Max/Min of a List or Collection
1. Overview
This tutorial is a quick intro on how to find the min and max values from a given list or collection with the powerful Stream API in Java 8.
2. Find Max in a List of Integers
We can use the max() method provided through the java.util.Stream interface, which accepts a method reference:
@Test public void whenListIsOfIntegerThenMaxCanBeDoneUsingIntegerComparator() { // given List<Integer> listOfIntegers = Arrays.asList(1, 2, 3, 4, 56, 7, 89, 10); Integer expectedResult = 89; // then Integer max = listOfIntegers .stream() .mapToInt(v -> v) .max().orElseThrow(NoSuchElementException::new); assertEquals("Should be 89", expectedResult, max); }
Let’s take a closer look at the code:
- Calling stream() method on the list to get a stream of values from the list
- Calling mapToInt(value -> value) on the stream to get an Integer Stream
- Calling max() method on the stream to get the max value
- Calling orElseThrow() to throw an exception if no value is received from max()
3. Find Min With Custom Objects
In order to find the min/max on custom objects, we can also provide a lambda expression for our preferred sorting logic.
Let’s first define the custom POJO:https://55a1df389598a4f4c6bbc11440e9196d.safeframe.googlesyndication.com/safeframe/1-0-38/html/container.html?upapi=trueAD
class Person { String name; Integer age; // standard constructors, getters and setters }
We want to find the Person object with the minimum age:
@Test public void whenListIsOfPersonObjectThenMinCanBeDoneUsingCustomComparatorThroughLambda() { // given Person alex = new Person("Alex", 23); Person john = new Person("John", 40); Person peter = new Person("Peter", 32); List<Person> people = Arrays.asList(alex, john, peter); // then Person minByAge = people .stream() .min(Comparator.comparing(Person::getAge)) .orElseThrow(NoSuchElementException::new); assertEquals("Should be Alex", alex, minByAge); }
Let’s have a look at this logic:
- Calling stream() method on the list to get a stream of values from the list
- Calling min() method on the stream to get the minimum value. We pass a lambda function as a comparator, and this is used to decide the sorting logic for deciding the minimum value.
- Calling orElseThrow() to throw an exception if no value is received from min()
4. Conclusion
In this quick article, we explored how the max() and min() methods from the Java 8 Stream API can be used to find the maximum and minimum value from a List or Collection.
As always, the code is available over on GitHub.
Credits : https://www.baeldung.com/java-collection-min-max