1. Introduction
A quick intro on how to find the min/max value from a given list/collection with the powerful Stream API in Java8.
2. Find Max in a List of Integers
We can use max() method provided through the java.util.Stream interface. It 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:
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 are passing a lambda function as a comparator, 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 Java 8's Stream API can be used to find the maximum and minimum value from a List/Collection.
As always, the code is available over on Github.