Categories
Java

Sort a list of objects in Java, in 1 line of code with method reference

In this tutorial, we will explain how to sort a list of Java objects based on a field of the object. Firstly, we will see a method using the method reference operator :: that takes only 1 line of code. Then we will see a more generic method based on a lambda comparator that needs 2 lines of code.

Let’s define the following POJO (or Bean) called User that has one field name:

@AllArgsConstructor
@Data
class User {
    String name;
}

@AllArgsConstructor and @Data are annotations from the Lombok project. They add constructors, setters and getters to the POJO User, so that we don’t have to write all this boilerplate code.

1) How to sort a List<User>

To sort a List<User> called users using a method reference, simply do:

users.sort(Comparator.comparing(User::getName));

To sort a List<User> called users using a lambda comparator, do:

Comparator<User> compareByName = (User u1, User u2) -> u1.getName().compareTo(u2.getName());
Collections.sort(users, compareByName);

2) Full code demo

For the demo, let’s write a function unorderedUsers() that generates an unordered list of User:

static List<User> unorderedUsers() {
    List<String> userNames = List.of("foo", "aaa", "az", "12", "toto", "foobar");
    return userNames.stream().map(User::new).collect(Collectors.toList());
}

Then, let’s put everything into a Main:

package com;

import java.util.*;

import lombok.*;

public class Main {
    public static void main(String[] args) {
        // unordered users
        List<User> users = unorderedUsers();
        System.out.println("Sort with method reference:");
        System.out.println(users);

        // sort with function reference
        users.sort(Comparator.comparing(User::getName));
        System.out.println(users);

        // unordered users
        users = unorderedUsers();
        System.out.println("Sort with lambda comparator:");
        System.out.println(users);

        // sort with lambda comparator
        Comparator<User> compareByName = (User u1, User u2) -> u1.getName().compareTo(u2.getName());
        Collections.sort(users, compareByName);
        System.out.println(users);
    }

    static List<User> unorderedUsers() {
        List<String> userNames = List.of("foo", "aaa", "az", "12", "toto", "foobar");
        return userNames.stream().map(User::new).collect(Collectors.toList());
    }
}

@AllArgsConstructor
@Data
class User {
    String name;
}

When you run the code above, you will get the following result in the console:

Sort with method reference:
[User(name=foo), User(name=aaa), User(name=az), User(name=12), User(name=toto), User(name=foobar)]
[User(name=12), User(name=aaa), User(name=az), User(name=foo), User(name=foobar), User(name=toto)]

Sort with lambda comparator:
[User(name=foo), User(name=aaa), User(name=az), User(name=12), User(name=toto), User(name=foobar)]
[User(name=12), User(name=aaa), User(name=az), User(name=foo), User(name=foobar), User(name=toto)]

Thank you for reading this tutorial ! If you need help, please leave us a reply below, we answer within 24 hours.

Leave a Reply

Your email address will not be published. Required fields are marked *