
Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:
Once the early-adopter seats are all used, the price will go up and stay at $33/year.
Last updated: April 4, 2025
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.
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:
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:
To determine the minimum or maximum value in an ArrayList, we can either use the method we saw earlier or the min() and max() methods of the Java Collections class. Those methods return the minimum and maximum element of a given collection, respectively.
Further, we can use the indexOf() method of the ArrayList class to get the index of an element in a list. This method returns the index of the first occurrence of an element in the list.
Let’s take this example:
List<Integer> listOfIntegers = Arrays.asList(11, 13, 9, 20, 7, 3, 30);
Integer expectedMinValue = 3;
Integer expectedMinIndex = 5;
Integer minValue = Collections.min(listOfIntegers);
Integer minIndex = listOfIntegers.indexOf(minValue);
assertEquals(minValue, expectedMinValue);
assertEquals(minIndex, expectedMinIndex);
First, we defined a list of Integers to store our values. Then we used Collections.min() to get the minimum value of the list, which in our case, equals three. Finally, we used listOfIntegers.indexOf() to get the index of this value in the list, which in our case, equals five.
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.