Sort a collection with lambda comparator

With Java 8 we can use a lambda expression to implement a Comparator for sorting a collection:

class Person {
    public String name;
    public int age;
// TODO we should add some persons to this list
List<Person> persons = new ArrayList<>();
// Using a lambda expression to implement the Comparator
Collections.sort(persons, (p1, p2) ->;

Before Java 8, we had to write code like this:

Collections.sort(persons, new Comparator<Person>() {
    public int compare(Person p1, Person p2) {

Subscribe to Java 8 Resources

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.