Java Comparator Custom Object Sorting Example

This source code example showcases the flexibility that Comparator offers when dealing with custom object sorting in Java.

The Comparator interface in Java provides a mechanism to define custom orderings for collections of objects, beyond their natural ordering. This becomes essential when you want to sort or order a collection based on specific attributes or fields of objects.

Sorting Custom Objects using Java's Comparator Interface

import java.util.Arrays;
import java.util.Comparator;

// Define a custom object: Student
class Student {
    String name;
    int marks;

    Student(String name, int marks) {
        this.name = name;
        this.marks = marks;
    }

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

public class CustomObjectSorting {
    public static void main(String[] args) {
        Student[] students = {
            new Student("Rohan", 85),
            new Student("Amit", 90),
            new Student("Pooja", 88)
        };

        // 1. Sorting by name using Comparator
        Arrays.sort(students, Comparator.comparing(Student::getName));
        System.out.println("Students sorted by name: " + Arrays.toString(students));

        // 2. Sorting by marks using Comparator
        Arrays.sort(students, Comparator.comparingInt(Student::getMarks));
        System.out.println("Students sorted by marks: " + Arrays.toString(students));

        // 3. Sorting by marks in descending order using Comparator
        Arrays.sort(students, Comparator.comparingInt(Student::getMarks).reversed());
        System.out.println("Students sorted by marks in descending order: " + Arrays.toString(students));
    }
}

Output:

Students sorted by name: [Amit (90), Pooja (88), Rohan (85)]
Students sorted by marks: [Rohan (85), Pooja (88), Amit (90)]
Students sorted by marks in descending order: [Amit (90), Pooja (88), Rohan (85)]

Explanation:

1. Sorting by name: The method Comparator.comparing(Student::getName) provides a comparator that sorts the Student objects based on their names alphabetically.

2. Sorting by marks: The method Comparator.comparingInt(Student::getMarks) provides a comparator that sorts Student objects based on their marks in ascending order.

3. Sorting by marks in descending order: By chaining the reversed() method to the above comparator, we achieve sorting in descending order of marks.

Using Comparator, we can define custom sorting logic for our objects without the need for them to implement the Comparable interface.


Comments