In  this tutorial, we will see “What is a maxBy() method in Java 8 and how we can use it?” maxBy java 8

maxBy() method in Java 8 with example...!!! Click To Tweet

Collectors maxBy() Method

Syntax & Description

Returns a Collector that produces the maximal element according to a given Comparator, described as an Optional<T>.

Syntax: static <T> Collector<T,?,Optional<T>> maxBy(Comparator<? super T> comparator)

Type Parameters:

<T> the type of the input elements


comparator a Comparator for comparing elements


a Collector that produces the maximal value

How to use it – an Example?



maxBy java 8

In this example, we have a list of Person objects and we want to find the oldest person in the list. We use the maxBy method with a Comparator that compares the ages of the persons and returns the person with the highest age. The maxBy method returns an Optional object, so we use the orElse method to get the actual person object or null if the list is empty.

skip method java 8 stream

Java 8 – Collectors maxBy() method with Example Click To Tweet

Do you like this Post? – then check my other helpful posts:

Other Useful References: