Course Content
Stream API
Stream API
Comparable: Natural Ordering of Data
In Java, it's common to need to sort objects. For example, in a list of books, you might want to sort them by title, author, or publication year.
To handle such tasks, Java provides the Comparable
and Comparator
interfaces. Both achieve the same goal (sorting objects) but they do so in different ways. Let's break them down one by one.
What Is Comparable?
For example, Java strings are sorted alphabetically by default because the String
class implements Comparable
.
The key method in the Comparable
functional interface is:
This method returns:
- A negative number if the current object is less than the given object;
- Zero if the objects are equal;
- A positive number if the current object is greater than the given object.
Example: Sorting Books by Year
Let's say you want to compare Book
objects based on their publication year.
To achieve this, the Book
class can implement Comparable
and override the compareTo
method. By overriding this method, you define how Book
objects should be compared, which directly affects the sorting behavior in methods like Collections.sort()
.
This allows us to control the order in which books are sorted—whether ascending or descending—based on the logic you implement in compareTo
.
Main
package com.example; import java.util.List; import java.util.ArrayList; import java.util.Collections; public class Main { public static void main(String[] args) { List<Book> books = new ArrayList<>(); books.add(new Book("Book A", "Author X", 2020)); books.add(new Book("Book B", "Author Y", 2018)); books.add(new Book("Book C", "Author Z", 2021)); Collections.sort(books); // Uses `compareTo` System.out.println(books); } } class Book implements Comparable<Book> { private String title; private String author; private int year; public Book(String title, String author, int year) { this.title = title; this.author = author; this.year = year; } public int getYear() { return year; } @Override public int compareTo(Book other) { return Integer.compare(this.year, other.year); // Compare by publication year } @Override public String toString() { return title + " (" + year + ")"; } }
When Collections.sort(books)
is called, Java iterates through the list, comparing elements using the compareTo
method defined in the Book
class.
For each comparison, compareTo
returns a numeric value that determines the order of two books. Based on these values, the sorting algorithm rearranges the elements so they are ordered by ascending publication year.
Thanks for your feedback!