Java Sorting with Comparable and Comparator
"Believer".compareTo("Perfect") is -14, so Believer goes first. A Song that implements Comparable sorts by title, a byPlays Comparator puts Thunder's 2100 plays on top, and thenComparing breaks the Imagine Dragons tie by title.
What you will learn
- Read compareTo and compare results: negative first, zero a tie, positive after
- Give a class its natural order by implementing Comparable
- Write a Comparator for a second order and pass it to Collections.sort
- Break a tie with thenComparing
Before you start
- Java ArrayList
- Java interfaces
Say you have a playlist of songs. Should Java sort them by title, by plays or by artist? It can't guess, so you tell it, using one of two interfaces: Comparable or Comparator.
compareTo says who comes first
package org.studyeasy.s04l09;
public class Ex01_CompareTo {
public static void main(String[] args) {
String a = "Believer";
String b = "Perfect";
// compareTo answers one question: who comes first?
System.out.println("Believer vs Perfect: " + a.compareTo(b));
System.out.println("Perfect vs Believer: " + b.compareTo(a));
System.out.println("Believer vs itself: " + a.compareTo(a));
// numbers follow the same rule
int gap = Integer.compare(950, 1500);
System.out.println("950 vs 1500: " + gap);
}
}
Believer vs Perfect: -14
Perfect vs Believer: 14
Believer vs itself: 0
950 vs 1500: -1
Sorting comes down to one question, and the answer is a number. B is 66 and P is 80, so 66 minus 80 gives -14: negative, Believer goes first. Turn the pair round and it's 14: positive, Perfect goes after. The same word gives 0, a tie. Integer.compare(950, 1500) follows the same rule. Negative first, zero tie, positive after. (a.compareTo(42) won't compile; a String compares only with a String.)
A song that knows its own order
package org.studyeasy.s04l09;
public class Song implements Comparable<Song> {
private String title;
private String artist;
private int plays;
public Song(String title, String artist, int plays) {
this.title = title;
this.artist = artist;
this.plays = plays;
}
public String getArtist() {
return artist;
}
public int getPlays() {
return plays;
}
@Override
public int compareTo(Song other) {
return title.compareTo(other.title); // natural order
}
@Override
public String toString() {
return title + " - " + artist + " (" + plays + ")";
}
}
implements Comparable<Song> tells Java songs can be compared and promises a compareTo. How they compare is the class author's choice: here, by title, A to Z.
List<Song> playlist = new ArrayList<>();
playlist.add(new Song("Thunder", "Imagine Dragons", 2100));
playlist.add(new Song("Perfect", "Ed Sheeran", 1200));
playlist.add(new Song("Believer", "Imagine Dragons", 1500));
// no order given, so sort calls Song.compareTo
Collections.sort(playlist);
for (Song song : playlist) {
System.out.println(song);
}
Believer - Imagine Dragons (1500)
Perfect - Ed Sheeran (1200)
Thunder - Imagine Dragons (2100)
With no order given, Collections.sort asks the songs themselves through compareTo. That's the natural order. Sort keeps comparing two songs at a time (Perfect vs Thunder is -4, Believer vs Perfect is -14) and the negative one goes first. Thunder has the most plays but comes last. Remove implements Comparable<Song> and the sort line won't compile: no suitable method found for sort.
A second order, from outside
// a second order, written outside Song as an anonymous class
Comparator<Song> byPlays = new Comparator<Song>() {
@Override
public int compare(Song a, Song b) {
return Integer.compare(b.getPlays(), a.getPlays());
}
};
// b before a: the song with more plays goes first
Collections.sort(playlist, byPlays);
Thunder - Imagine Dragons (2100)
Believer - Imagine Dragons (1500)
Perfect - Ed Sheeran (1200)
The title order is already inside Song, so a second order is written outside, as a Comparator (here an anonymous class). Its compare takes two songs. Note b comes before a: the song with more plays gets the negative number and goes first. Pass the comparator to sort and it ignores compareTo. Swap to a before b and the order flips to least played first. The songs didn't change; only the rule did.
A tie? Ask the next rule
Comparator<Song> byArtist = new Comparator<Song>() {
@Override
public int compare(Song a, Song b) {
return a.getArtist().compareTo(b.getArtist());
}
};
// same artist? then fall back to the natural order (title)
Comparator<Song> order =
byArtist.thenComparing(Comparator.naturalOrder());
Collections.sort(playlist, order);
Perfect - Ed Sheeran (1200)
Believer - Imagine Dragons (1500)
Thunder - Imagine Dragons (2100)
Ed Sheeran comes before Imagine Dragons, so Perfect goes first. The two Imagine Dragons songs tie on artist, so thenComparing asks the next rule, Comparator.naturalOrder(), which is the title. With byArtist alone, Thunder stays ahead of Believer simply because it was added first.
Comparable or Comparator
| Comparable | Comparator | |
|---|---|---|
| Lives | inside the class | outside, in its own object |
| Method | compareTo(other) | compare(a, b) |
| Orders | one, the natural order | as many as you write |
| Sort call | Collections.sort(playlist) | Collections.sort(playlist, byPlays) |
An AI can write the comparators; you need the idea to read them and ask for the right one. With lambdas, byPlays shrinks to one line.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Java equals and hashCode: Why a HashSet Needs Both
== asks if it's the very same object, equals compares values, and hashCode puts equal objects in the same HashSet bucket. Three small programs show what breaks when hashCode is missing.
From Arrays to Collections: The Java Collections Framework Map
An array of 3 students can't seat John, so Java throws Index 3 out of bounds. A List just grows. Then the map of the framework: List, Set and Queue under Collection, Map beside it, four behaviours in one program, and why the variable type should be the interface.
Java Wrapper Classes and Autoboxing
List<int> won't compile because a list holds objects only. Integer.valueOf puts 87 in a box and intValue takes it out, and add and get do it for you. Then two traps: 128 == 128 is false, and unboxing a null Integer throws a NullPointerException.
Java ArrayList: The Stretchy Array
add, add at an index, get, set, remove and contains on a list of courses and a cart, why Git at index 1 pushes SQL and Spring right, removing scores below 50 with an Iterator or removeIf, List.of that can't change, and the array inside that grows from 10 to 15.
