Skip to main content

How to sort list of objects in java with examples

How to Sort a List of Objects in Java: Complete Guide with Examples

Java Object Sorting Workflow Java Object Sorting Workflow 1 Define Custom Class Create domain models with multiple fields like Employee. 2 Identify Sorting Need Determine if natural or custom sorting is required. 3 Implement Comparable Add natural ordering via compareTo() inside the target class. 4 Implement Comparator Create external sorting strategies via compare() methods. 5 Execute Sort Operation Sort the list using Collections.sort() with defined criteria.
Figure: Java Object Sorting Workflow

Sorting a collection of custom objects is a fundamental operation in enterprise software development. Whether you are generating reports, building REST APIs, or preparing datasets for database insertion, organizing domain models into a deterministic sequence is required. In Java, sorting object lists is handled primarily through two core contracts in the java.util package: Comparable and Comparator.

Pick a language, then press Listen.

This tutorial provides a complete walkthrough of sorting custom object lists in Java. You will learn how to implement natural ordering, apply custom sorting strategies, handle complex multi-field criteria, and avoid common runtime pitfalls.


The Problem Statement

Consider a scenario where you retrieve a List<Employee> from a database or an external microservice. By default, Java does not know how to order instances of a custom class like Employee because it has multiple fields (such as fname and lname). If you pass this list directly to Collections.sort() without providing sorting logic, the compiler throws a compilation error or the runtime throws a ClassCastException.

To fix this, you must define the sorting criteria. Java offers two distinct mechanisms to achieve this:

  1. Comparable interface: Defines the natural ordering of a class. The class itself implements this interface, meaning the object knows how to compare itself to another instance of the same type.
  2. Comparator interface: Defines a custom ordering strategy external to the class being sorted. You can create multiple comparator implementations to sort the same object by different fields (e.g., sort by last name, first name, or hire date).

Core Concepts: Comparable vs. Comparator

Before writing code, it is vital to understand the structural and logical differences between these two interfaces. Choosing the right approach depends on whether you control the source code of the class and whether you need multiple sorting sequences.

Feature java.lang.Comparable java.util.Comparator
Package java.lang java.util
Method Name compareTo(T o) compare(T o1, T o2)
Number of Arguments One argument (compares this with the argument). Two arguments (compares o1 with o2).
Sorting Sequence Provides a single, default natural ordering. Allows multiple custom sorting strategies.
Source Code Modification Requires modifying the target class. Externalized; does not require modifying the target class.
Common Use Case Primary business keys (e.g., ID, Timestamp, Natural Name). Secondary sorting, alternate views (e.g., sort by salary, age).

Both methods (compareTo and compare) return an integer value based on the relative ordering of the elements:

  • Negative integer (e.g., -1): The first object is less than the second object.
  • Zero (0): Both objects are equal in terms of the sorting criteria.
  • Positive integer (e.g., 1): The first object is greater than the second object.

Method 1: Sorting Using the Comparable Interface

Use the Comparable interface when a class has a clear, default sorting order. For modern Java applications, you can also explore Java 17 Records and Pattern Matching with Examples for immutable data carriers that naturally support compact class definitions.

Step 1: Create the Employee Class

Implement the generic Comparable<Employee> interface and override the compareTo method to sort employees by their last name (lname).

package com.javatbrains.compare;

public class Employee implements Comparable<Employee> {
    private String fname;
    private String lname;

    public Employee(String fname, String lname) {
        this.fname = fname;
        this.lname = lname;
    }

    public String getFname() {
        return fname;
    }

    public String getLname() {
        return lname;
    }

    @Override
    public int compareTo(Employee other) {
        // Delegate comparison to String's natural ordering
        return this.lname.compareTo(other.getLname());
    }

    @Override
    public String toString() {
        return fname + " " + lname;
    }
}

Step 2: Write the Execution Class

Create a runner class that instantiates a list of employees, invokes Collections.sort(), and prints the sorted output.

package com.javatbrains.compare;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class EmployeeComparable {
    public static void main(String[] args) {
        List<Employee> empList = new ArrayList<>();
        empList.add(new Employee("Subba", "Reddy"));
        empList.add(new Employee("Samba", "Siva"));
        empList.add(new Employee("Nalla", "Machu"));

        // Sort using natural ordering defined in Comparable
        Collections.sort(empList);

        System.out.println("Employees sorted by Last Name (Comparable):");
        for (Employee e : empList) {
            System.out.println(e);
        }
    }
}

Expected Output

Employees sorted by Last Name (Comparable):
Nalla Machu
Subba Reddy
Samba Siva

Method 2: Sorting Using the Comparator Interface

When you need to sort objects by multiple attributes—such as sorting first by last name and then by first name—or when you cannot modify the original class, use the Comparator interface.

Step 1: Create a Custom Comparator Class

Create a class that implements Comparator<Employee>. This design keeps sorting logic cleanly separated from the domain model.

package com.javatbrains.compare;

import java.util.Comparator;

public class EmployeeFirstNameComparator implements Comparator<Employee> {
    @Override
    public int compare(Employee e1, Employee e2) {
        return e1.getFname().compareTo(e2.getFname());
    }
}

Step 2: Apply the Comparator in Code

Pass an instance of the comparator as the second argument to Collections.sort(), or use the modern List.sort() method introduced in Java 8.

package com.javatbrains.compare;

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

public class EmployeeComparatorTest {
    public static void main(String[] args) {
        List<Employee> empList = new ArrayList<>();
        empList.add(new Employee("Subba", "Reddy"));
        empList.add(new Employee("Samba", "Siva"));
        empList.add(new Employee("Nalla", "Machu"));

        // Sort using Java 8 List.sort() with a Comparator
        empList.sort(new EmployeeFirstNameComparator());

        System.out.println("Employees sorted by First Name (Comparator):");
        for (Employee e : empList) {
            System.out.println(e);
        }
    }
}

Expected Output

Employees sorted by First Name (Comparator):
Nalla Machu
Samba Siva
Subba Reddy

Advanced Sorting: Lambda Expressions and Method References

Writing standalone comparator classes for every sorting requirement leads to boilerplate code. Since Java 8, you can write inline comparators using lambda expressions and factory methods like Comparator.comparing().

package com.javatbrains.compare;

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

public class EmployeeLambdaSort {
    public static void main(String[] args) {
        List<Employee> empList = new ArrayList<>();
        empList.add(new Employee("Subba", "Reddy"));
        empList.add(new Employee("Samba", "Siva"));
        empList.add(new Employee("Nalla", "Machu"));

        // Sort by last name using Comparator.comparing lambda
        empList.sort(Comparator.comparing(Employee::getLname));

        // Multi-field sorting: sort by last name, then by first name
        empList.sort(Comparator.comparing(Employee::getLname)
                               .thenComparing(Employee::getFname));

        // Reverse chronological / descending order sorting
        empList.sort(Comparator.comparing(Employee::getLname).reversed());
    }
}

If you are deploying containerized microservices that process these sorted records and connect to relational backends, refer to Dockerizing a Spring Boot Application with MySQL for configuration guidelines.


Real-World Edge Cases to Handle

Production environments introduce data irregularities that can break naive sorting implementations. Keep these edge cases in mind when writing production-grade Java sorting logic:

1. Handling Null Values in Lists

If your list contains null elements or if properties within your objects return null, calling comparison methods directly throws a NullPointerException. Use Comparator.nullsFirst() or Comparator.nullsLast() to safely manage null references.

// Safely sort even if lname is null
empList.sort(Comparator.comparing(Employee::getLname, Comparator.nullsLast(String::compareTo)));

2. Case-Insensitive String Sorting

Standard Java string comparison (String.compareTo) is case-sensitive, meaning uppercase characters ("Z") sort before lowercase characters ("a"). For human-readable reports, use case-insensitive sorting.

// Case-insensitive sorting
empList.sort((e1, e2) -> e1.getLname().compareToIgnoreCase(e2.getLname()));

3. Sorting Immutable or Legacy Objects

When working with legacy codebases or database abstraction layers that configure connection pools through enterprise naming services—similar to setups discussed in JNDI configuration for Tomcat 9 with Oracle—you cannot alter third-party domain classes to implement Comparable. Always use external Comparator instances for immutable or third-party library classes.


Troubleshooting Common Errors

  • ClassCastException: Thrown when objects in a collection do not implement Comparable and no Comparator is supplied to the sorting method. Ensure your class implements Comparable<T> or pass an explicit comparator to Collections.sort().
  • NullPointerException during sorting: Occurs when a property evaluated in a comparator returns null. Wrap your comparators using Comparator.nullsFirst() or filter out null objects before sorting.
  • Unstable Sorting Results: If two objects evaluate as equal according to your primary sort key (e.g., two employees sharing the same last name), their relative order might change if you do not define a secondary sorting criteria using thenComparing().

Summary

  • Use Comparable when defining the single, natural sorting order directly inside your domain class.
  • Use Comparator when you need multiple sorting strategies or cannot modify the target class source code.
  • Leverage Java 8+ features like Comparator.comparing(), thenComparing(), and lambda expressions to write clean, maintainable sorting code.
  • Always guard against production edge cases like null properties and case sensitivity to prevent runtime exceptions.

Comments

Popular posts from this blog

JVM, JRE and JDK in Java

Understanding JVM, JRE, and JDK in Java Every Java developer encounters three fundamental acronyms on their first day: JVM , JRE , and JDK . Misunderstanding these foundational components leads to runtime exceptions, deployment failures, and incorrect build environments. This guide breaks down the precise architectural boundaries, memory structures, and deployment requirements of each component. ▶ Listen English (India) English (US) Hindi Telugu Tamil Kannada Malayalam Bengali Marathi Gujarati Punjabi Urdu Arabic Spanish French German Portuguese Japanese Korean Chinese (Simplified) Pick a language, then press Listen. The core problem this guide solves is ambiguous environment configuration. Developers often attempt to run production applications using a Development Kit when a Runtime Environment suffices, or they deploy platform-incompatible binaries to minimal Li...

Prime, Fibonacci and Factorial number with example in java

Mastering Prime, Fibonacci, and Factorial Algorithms in Java Prime Number Validation Workflow Prime Number Validation Workflow 1 Boundary Check Verify if the input number is less than or equal to 1. 2 Even Number Check Check if divisible by 2 and return true only if number is 2. 3 Square Root Limit Calculate integer square root as the upper loop bound. 4 Odd Factor Loop Iterate through odd integers up to limit checking divisibility. Figure: Prime Number Validation Workflow Technical coding interviews frequently test foundational algorithmic competence through three classic mathematical problems: identifying prime numbers, generating Fibonacci sequences, and calculating factorials. While these concepts originate in basic arithmetic, writing production-grade Java code to solve them requires careful attention to time complexity, memory allocation, boundary conditions, and overflow behavior. This tutorial provides rigorous, optimized Java i...

How to insert images into database using JDBC?

How to Insert Images into a Database Using JDBC Storing binary data such as images, PDFs, and application assets is a frequent requirement in enterprise software engineering. While relational databases like MySQL are optimized for structured tabular text and numeric data, they also provide robust binary storage types—specifically BLOB (Binary Large Object) variants—to handle arbitrary byte streams. When interacting with relational stores through Java, the Java Database Connectivity (JDBC) API serves as the primary bridge. ▶ Listen English (India) English (US) Hindi Telugu Tamil Kannada Malayalam Bengali Marathi Gujarati Punjabi Urdu Arabic Spanish French German Portuguese Japanese Korean Chinese (Simplified) Pick a language, then press Listen. This technical guide demonstrates how to persist image files from a local file system directly into a MySQL database usin...