Java natural sort (Comparable) with lambda

In this example, we can see the class Person and we use stream’s sorted() method to sort the list of people by their age. So in order for sorted() to work, it needs to have a natural order. For this reason, we have to implement the Comparable interface for the class which needs to be sorted.

The documentation for sorted() states:

“Returns a stream consisting of the elements of this stream, sorted according to natural order. If the elements of this stream are not Comparable, a java.lang.ClassCastException may be thrown when the terminal operation is executed.

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

This is a stateful intermediate operation.”

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

public class Main {
    static class Person implements Comparable<Person> {
        private String name;
        private Integer age;

        public Person(String name, Integer age) {
            this.name = name;
            this.age = age;
        }

        public String getName() {
            return name;
        }

        public Integer getAge() {
            return age;
        }

        @Override
        public String toString() {
            return "Person{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }

        @Override
        public int compareTo(Person person) {
            return this.age.compareTo(person.getAge());
        }
    }

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

        // Sort by natural order
        List<Person> sortedPeopleList = people
                .stream()
                .sorted()
                .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));
    }
}
Youngest person: Person{name='Tom', age=13}
Oldest person: Person{name='Jim', age=56}

Let’s see a similar implementation with Record for Person. We can see how much less code is needed:

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

public class MainClass {
    record Person (String name, Integer age) implements Comparable<Person> {
        @Override
        public int compareTo(Person person) {
            return this.age.compareTo(person.age());
        }
    }

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

        // Sort by natural order
        List<Person> sortedPeopleList = people
                .stream()
                .sorted()
                .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));
    }
}
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.