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...!!! Share on X
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
Parameters:
comparator a Comparator for comparing elements
Returns:
a Collector that produces the maximal value
How to use it – an Example?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | /** * Using maxBy method as name suggest, Find the person with the max age * @author Deepak Verma * */ import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; public class maxBy_Collectors_Method_Java8_Example { public static void main(String args[]) { List<Person> people = Arrays.asList( new Person("Yashika", 17), new Person("Deepak", 37), new Person("Yash", 17), new Person("Isha", 32), new Person("Gaurangee", 21) ); Person oldestPerson = people.stream() .collect(Collectors.maxBy(Comparator.comparing(Person::getAge))) .orElse(null); System.out.println("Older Person among the list is: "+oldestPerson.getName()); } } |
Output:
1 | Older Person among the list is: Deepak |
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 Share on X
Do you like this Post? – then check my other helpful posts:
- Convert a Stream to a List in Java 8
- Stream maptoint in Java 8 with examples
- Double the numbers of specified ArrayList using Streams
- Double the even / odd numbers of a specified ArrayList using Streams
- How to check if Number is Prime or not using Streams
- Retrieve Even/Odd Numbers within the Range using Java 8 Streams
- How to add/sum up the ArrayList integers using Java8 Streams
- Generate Prime Numbers in Java 8 using Streams
- Comparator example – Collections sort with/without Lambda in Java 8
- How to pass function as a parameter in a method in Java 8?
- Remove duplicates from ArrayList in Java 8
- ForEach examples for Map/List in Java 8
Other Useful References: