Java 17 sort (Comparable) with lambda and Record

In this example we can see record Person and we use stream’s sorted(Comparator<? super T> comparator) method to sort the List of people by their age. So sorted(Comparator<? super T> comparator) accept as parameter Comparator. For this reason we have to create Comparator and we sort inside by age.

The documentation for sorted(Comparator<? super T> comparator) state:

Returns a stream consisting of the elements of this stream, sorted according to the provided Comparator.

For ordered streams, the sort is stable. For unordered streams, no stability guarantees are made.

This is a stateful intermediate operation.

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class MainClassTest {
    record Person (String name, Integer age) {}

    public static void main(String[] args)
    {
        List<Person> people = List.of(
                new Person("Jim", 56),
                new Person("Tom", 13),
                new Person("Maria", 20)
        );

        Comparator<Person> ageComparator = (p1, p2) -> p1.age().compareTo(p2.age);

        // Sort by natural order
        List<Person> sortedPeopleList = people
                .stream()
                .sorted(ageComparator)
                .collect(Collectors.toList());

        // get the youngest person
        System.out.println("Youngest person: " + sortedPeopleList.get(0));
        // get the oldest person
        Integer lastIndex = sortedPeopleList.size() - 1;
        System.out.println("Oldest person: " + sortedPeopleList.get(lastIndex));
    }
}

Output:

Youngest person: Person[name=Tom, age=13]
Oldest person: Person[name=Jim, age=56]

Leave a Comment

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.