How do we sort list of Objects in Java?

In Java, you can sort a List of objects using:

  1. Comparable interface (natural ordering)
  2. Comparator interface (custom ordering)
  3. Lambda expressions (Java 8+)

✅ Example Object

public class Student {
    private String name;
    private int age;

    // constructor, getters, setters
}

 

🔹 1. Using Comparable (Natural Order)

Implement Comparable<T> in the class:

public class Student implements Comparable<Student> {
    private String name;
    private int age;

    @Override
    public int compareTo(Student other) {
        return this.age - other.age; // ascending by age
    }
}

Then:

Collections.sort(studentList);

🔹 2. Using Comparator (Custom Order)

Collections.sort(studentList, new Comparator<Student>() {
    public int compare(Student s1, Student s2) {
        return s1.getName().compareTo(s2.getName()); // sort by name
    }
});

🔹 3. Using Lambda (Cleanest in Java 8+)

studentList.sort((s1, s2) -> s1.getAge() - s2.getAge()); // by age

// Or by name
studentList.sort(Comparator.comparing(Student::getName));


🔄 Reverse Order Example

studentList.sort(Comparator.comparing(Student::getAge).reversed());

🧠 Summary

Method Use When
Comparable Natural/default ordering
Comparator Multiple/custom sort logics
Lambda Short, inline comparisons

Back to blog

Leave a comment

Please note, comments need to be approved before they are published.