How do I sort a list of objects by a field in Java?

You can use Comparator.comparing() to sort objects by a field exposed through an accessor method.

In this example, you will sort a list of books alphabetically by title.

Source code

Save the following code as SortObjectsExample.java:

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class SortObjectsExample {
    void main() {
        List<Book> books = new ArrayList<>(List.of(
                new Book("Learning Java", "Alice"),
                new Book("Exploring Java", "Bob"),
                new Book("Building Java Apps", "Carol")
        ));

        books.sort(Comparator.comparing(Book::title));

        for (Book book : books) {
            IO.println(book.title() + " by " + book.author());
        }
    }
}

record Book(String title, String author) {
}

Explanation

The Book record stores a title and an author:

record Book(String title, String author) {
}

Java provides the accessor methods title() and author() automatically.

The example creates an ArrayList containing three books. This list supports sorting, unlike the unmodifiable list returned directly by List.of().

Creating a comparator

The following expression creates a comparator that compares books by title:

Comparator.comparing(Book::title)

The method reference Book::title tells the comparator which value to extract from each book.

Because the extracted values are strings, the comparator uses their natural ordering. For these titles, that produces alphabetical order. String natural ordering is case-sensitive.

Sorting the list

Pass the comparator to sort():

books.sort(Comparator.comparing(Book::title));

This rearranges the elements in the existing list. It does not create a separate sorted list.

The loop then prints the books in their new order:

for (Book book : books) {
    IO.println(book.title() + " by " + book.author());
}

Run the example

Compile and run the file:

javac SortObjectsExample.java
java SortObjectsExample

Output

Building Java Apps by Carol
Exploring Java by Bob
Learning Java by Alice

Reversing the order

To sort titles in descending order, reverse the comparator:

books.sort(Comparator.comparing(Book::title).reversed());

Comparing another field when titles match

Use thenComparing() to compare authors when two books have equal titles:

books.sort(
        Comparator.comparing(Book::title)
                .thenComparing(Book::author)
);

This sorts by title first, then by author for books with matching titles.