0
0
JavaHow-ToBeginner · 3 min read

How to Sort List of Objects in Java: Simple Guide

To sort a list of objects in Java, use Collections.sort() with objects implementing Comparable or provide a Comparator to define custom sorting logic. This lets you order objects by any property you choose.
📐

Syntax

Use Collections.sort(list) if your objects implement Comparable. For custom sorting, use Collections.sort(list, comparator) where comparator defines the order.

Comparable: Implement compareTo() in your class to define natural order.

Comparator: Create a separate class or lambda that implements compare() to define custom order.

java
Collections.sort(list);
Collections.sort(list, comparator);
💻

Example

This example shows sorting a list of Person objects by their age using Comparable and then by name using a Comparator.

java
import java.util.*;

class Person implements Comparable<Person> {
    String name;
    int age;

    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public int compareTo(Person other) {
        return Integer.compare(this.age, other.age); // sort by age
    }

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

public class SortObjectsExample {
    public static void main(String[] args) {
        List<Person> people = new ArrayList<>();
        people.add(new Person("Alice", 30));
        people.add(new Person("Bob", 25));
        people.add(new Person("Charlie", 30));

        // Sort by age (natural order)
        Collections.sort(people);
        System.out.println("Sorted by age: " + people);

        // Sort by name using Comparator
        Collections.sort(people, Comparator.comparing(p -> p.name));
        System.out.println("Sorted by name: " + people);
    }
}
Output
Sorted by age: [Bob (25), Alice (30), Charlie (30)] Sorted by name: [Alice (30), Bob (25), Charlie (30)]
⚠️

Common Pitfalls

  • Not implementing Comparable or providing a Comparator causes ClassCastException.
  • For Comparable, compareTo() must be consistent with equals() to avoid unexpected behavior.
  • Modifying the list while sorting can cause errors.
  • Using incorrect comparison logic (e.g., subtracting integers directly) can cause overflow bugs.
java
/* Wrong: subtracting can overflow */
@Override
public int compareTo(Person other) {
    return this.age - other.age; // risky if ages are large
}

/* Right: use Integer.compare */
@Override
public int compareTo(Person other) {
    return Integer.compare(this.age, other.age);
}
📊

Quick Reference

Remember these tips when sorting objects in Java:

  • Use Comparable for natural order inside the class.
  • Use Comparator for flexible or multiple sorting criteria.
  • Use Collections.sort() or List.sort() to sort lists.
  • Prefer Integer.compare() or Comparator.comparing() for safe comparisons.

Key Takeaways

Implement Comparable or provide a Comparator to define object sorting order.
Use Collections.sort() with or without a Comparator to sort lists of objects.
Avoid subtracting integers directly in compareTo to prevent overflow bugs.
Comparator allows flexible sorting without changing the object's class.
Always ensure compareTo and equals are consistent to avoid unexpected results.