Skip to content

Java comparators

Java comparators—a powerful tool that adds finesse and elegance to your sorting adventures. Join me as we explore this enchanting world together, blending technical insights with a personal touch.

Java comparator is a special object that allows you to customize the way objects are sorted. Whether you're sorting strings, numbers, or custom objects, the Java comparator empowers you to define your own sorting rules with ease.

Imagine you're arranging a collection of books on a shelf. Some people like to sort them alphabetically by title, while others prefer to sort them by author's name. With Java comparators, you can tailor your sorting logic to suit your preferences, making your code as organized as a well-curated bookshelf.

Simple example to see the Java comparator:

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

class Book {
    private String title;
    private String author;

    public Book(String title, String author) {
        this.title = title;
        this.author = author;
    }

    public String getTitle() {
        return title;
    }

    public String getAuthor() {
        return author;
    }

    @Override
    public String toString() {
        return title + " by " + author;
    }
}

public class ComparatorExample {
    public static void main(String[] args) {
        Book[] books = {
            new Book("The Great Gatsby", "F. Scott Fitzgerald"),
            new Book("To Kill a Mockingbird", "Harper Lee"),
            new Book("1984", "George Orwell")
        };

        // Sort books by title
        Arrays.sort(books, Comparator.comparing(Book::getTitle));

        // Print sorted books
        for (Book book : books) {
            System.out.println(book);
        }
    }
}

In this example, we have a custom Book class representing books with titles and authors. We then create an array of Book objects and use the Arrays.sort() method along with a comparator to sort the books by their titles. It's like organizing your bookshelf alphabetically by book title!

But wait, there's more to the Java comparator than simple sorting! You can also create complex sorting rules, handle null values gracefully, and even chain multiple comparators together to achieve precise sorting logic.

Example

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

class Student {
    private String name;
    private int age;

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

public class ComparatorExample {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<>();
        students.add(new Student("Alice", 20));
        students.add(new Student("Bob", 18));
        students.add(new Student("Charlie", 22));

        // Sort students by age using a Comparator
        Collections.sort(students, new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
                return s1.getAge() - s2.getAge();
            }
        });

        // Print sorted students
        for (Student student : students) {
            System.out.println(student.getName() + ": " + student.getAge() + " years old");
        }
    }
}

In this example, we have a list of Student objects that we want to sort by age. We achieve this using a Comparator—an anonymous inner class that compares the ages of two students.

Now, let's break it down:

  • We define a Student class with name and age attributes.
  • In our ComparatorExample, we create a list of Student objects and add some students to it.
  • We use Collections.sort() to sort the list of students, passing in a Comparator that compares their ages.
  • Finally, we print the sorted list of students.

Waytojava is designed to make learning easier. We simplify examples for better understanding. We regularly check tutorials, references, and examples to correct errors, but it's important to remember that humans can make mistakes.