Java  

How Can I Sort a List of Objects by Property in Java?

Intorduction

Sorting data is one of the most common tasks in programming. In Java, you often work with lists of objects, and sometimes you need to sort these objects based on one of their properties. For example, you might have a list of Employee objects and want to sort them by their salary, name, or age. In this article, we will learn, in simple terms, how to sort a list of objects by property in Java using various approaches.

What Does It Mean to Sort Objects by Property?

When we say sorting objects by property, it means arranging them in a particular order (ascending or descending) based on a specific field inside the object. For example:

  • Sorting students by marks

  • Sorting employees by salary

  • Sorting products by price

In Java, we can achieve this using Comparable, Comparator, Lambdas, and the Streams API.

Using Comparable Interface

The Comparable interface allows objects of a class to be compared with each other. You define the natural ordering of the class.

Example: Sort Employees by ID

import java.util.*;

class Employee implements Comparable<Employee> {
    int id;
    String name;

    Employee(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public int compareTo(Employee other) {
        return this.id - other.id; // Ascending order by ID
    }

    @Override
    public String toString() {
        return id + " - " + name;
    }
}

public class Main {
    public static void main(String[] args) {
        List<Employee> employees = new ArrayList<>();
        employees.add(new Employee(3, "John"));
        employees.add(new Employee(1, "Alice"));
        employees.add(new Employee(2, "Bob"));

        Collections.sort(employees);
        System.out.println(employees);
    }
}

πŸ‘‰ Output: [1 - Alice, 2 - Bob, 3 - John]

Here, the list is sorted by employee ID in ascending order.

Using Comparator Interface

If you want to sort by different properties without changing the original class, use Comparator.

Example: Sort Employees by Name

import java.util.*;

class Employee {
    int id;
    String name;

    Employee(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public String toString() {
        return id + " - " + name;
    }
}

public class Main {
    public static void main(String[] args) {
        List<Employee> employees = new ArrayList<>();
        employees.add(new Employee(3, "John"));
        employees.add(new Employee(1, "Alice"));
        employees.add(new Employee(2, "Bob"));

        employees.sort(Comparator.comparing(emp -> emp.name));

        System.out.println(employees);
    }
}

πŸ‘‰ Output: [1 - Alice, 2 - Bob, 3 - John]

Here, we sorted by employee name in alphabetical order.

Using Lambda Expressions

Java 8 introduced lambda expressions, making sorting more concise.

Example: Sort Employees by ID (Descending)

employees.sort((e1, e2) -> e2.id - e1.id);

πŸ‘‰ This will sort the employees in descending order by ID.

Using Streams API

The Streams API in Java 8+ provides an elegant way to sort lists.

Example: Sort Employees by Name

employees.stream()
        .sorted(Comparator.comparing(emp -> emp.name))
        .forEach(System.out::println);

Example: Sort Employees by ID (Descending)

employees.stream()
        .sorted((e1, e2) -> e2.id - e1.id)
        .forEach(System.out::println);

πŸ‘‰ Streams API is useful when you want to sort and immediately process the data.

Sorting in Ascending vs Descending Order

  • Ascending Order β†’ Smallest to largest (A β†’ Z, 1 β†’ 100)

  • Descending Order β†’ Largest to smallest (Z β†’ A, 100 β†’ 1)

You can easily reverse the order using reversed():

employees.sort(Comparator.comparing(emp -> emp.name).reversed());

πŸ‘‰ This sorts employees by name in reverse alphabetical order.

Best Practices

  1. βœ… Use Comparable when you want a default natural order for objects.

  2. βœ… Use Comparator when sorting can vary depending on requirements.

  3. βœ… Use Lambdas for short and clean code.

  4. βœ… Use Streams API when combining sorting with filtering, mapping, or other operations.

Summary

Sorting a list of objects by property in Java is simple and powerful. You can use Comparable for natural ordering, Comparator for flexible custom sorting, Lambda expressions for cleaner code, and the Streams API for modern functional-style programming. Whether you’re working with names, salaries, prices, or IDs, these tools help you write clean, efficient, and SEO-friendly Java code. Mastering these techniques will make your Java applications more efficient and easier to maintain.