← All Exercises

Java Lambda Comparators

intermediatejava~20min

Background

Lambda expressions and method references enable concise comparator construction in Java 8+.

Problem

Write a Java method that sorts a list of Person objects by age descending, then name ascending, using lambda comparators.

Input

A list of Person objects with name and age fields.

Output

The list sorted by age descending, then name ascending.

Sample tests

Sample 1

Input: [{Bob,30},{Alice,25},{Carol,30}]
Expected: [{Bob,30},{Carol,30},{Alice,25}]

Your solution

Learning objective

Learn lambda comparators, Comparator.composing chains, and the reversed/thenComparing methods.