Java Collectors MaxBy Example

The Java 8 Collectors maxBy method returns the maximum element in a stream. This method has the following signature.

1
<T> Collector<T,?,Optional<T>> maxBy(Comparator<? super T> comparator)

Let’s look at an example of using the maxBy method to return the maximum integer value in a stream.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
@Test
public void maxBy() {
    List<Integer> numbersList = List.of(1, 2, 3, 4, 4, 5);

    Optional<Integer> maxNumber = numbersList.stream().collect(
        Collectors.maxBy(Integer::compareTo));

    Integer expected = 5;

    assertEquals(expected, maxNumber.get());
}

As we can see in the above code the Collectors.maxBy method uses a comparator to find the maximum element. In the code example we use the Integer.compareTo method to find the maximum element.

1
Collectors.maxBy(Integer::compareTo)

Conclusion

In this tutorial we looked at the Collectors.maxBy method that was added in Java 8. We showed that this method can be used to find the maximum element in a stream.