Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Java
  • Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program
  • Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA
  • Java Hello World with Maven: What the JDK Does and What Maven Adds
  • Java Variables, Keywords and Naming Rules
  • Maven in IntelliJ: pom.xml, Dependencies and the Build Lifecycle
  • Java Primitive Types and Memory: What int x = 5 Really Does
  • Java Strings and Text Blocks: Quotes, Concatenation and parseInt
  • Java Operators: Arithmetic, a++ vs ++a, Precedence, && || and the Ternary
  • Java Type Casting: Widening, Narrowing and Converting Text to Numbers
  • Java Practice Lab: A Cafe Bill with Variables, Operators and Casting
  • Java if, else and switch: Braces, Else-If Ladders and the Modern Switch
  • Java Loops: for, while, do-while and for-each
  • Java break, continue and Nested Loops
  • What's New in Java 21 to 25: Compact Source Files and Sequenced Collections
  • Java Arrays: Indexes, Default Values, Loops and 2D Grids
  • Java Methods and Overloading: Parameters, return and Pass-by-Value
  • Java Scope, Code Blocks and the Call Stack
  • Read User Input in Java with Scanner (and the Leftover Enter Trap)
  • Java Practice Lab: A Gym Weekly Tracker with Loops, Arrays and Methods
  • Debugging Java in IntelliJ: Stack Traces, Breakpoints and a Better AI Prompt
  • Java var: Let Java Infer the Type
  • Push and Pull in IntelliJ: Two Developers, One GitHub Repository, a Rejected Push and a Conflict
  • Java Classes and Objects: One Blueprint, Many Cars
  • Java Constructors and the this Keyword
  • Java Instance Methods, Getters, Setters and toString
  • Java static: Fields, Methods and Blocks Shared by the Whole Class
  • Java Packages and Imports: Every Class Has an Address
  • Java Access Modifiers and Encapsulation: Private Data, Public Methods
  • Java final and Immutable Objects: Assign Once, Share Safely
  • Java Strings as Objects: The String Pool, == vs equals, StringBuilder and printf
  • Java Practice Lab: A Library Book Catalogue with final Fields and StringBuilder
  • Java Inheritance: extends, super and the Order Objects Are Built
  • Java Method Overriding, @Override and the Object Class
  • Java Polymorphism: Upcasting, Dynamic Dispatch and Downcasting
  • Java Composition: Has-A vs Is-A
  • Java Abstract Classes: A Parent That Leaves One Blank
  • Java Interfaces: Contracts and Multiple Inheritance
  • Java Nested, Inner and Anonymous Classes
  • Java Enums with Fields, Methods and switch
  • Java Practice Lab: Payment Processing with an Interface, an Abstract Class and an Enum
  • Java Records: A Whole Data Class in One Line
  • Java Sealed Classes and Interfaces
  • Java Pattern Matching with instanceof and switch
  • Java Record Patterns: Unpacking a Record
  • Java equals and hashCode: Why a HashSet Needs Both
  • From Arrays to Collections: The Java Collections Framework Map
  • Java Wrapper Classes and Autoboxing
  • Java ArrayList: The Stretchy Array
  • Java LinkedList vs ArrayList: Nodes or an Array
  • Java Sets: HashSet, LinkedHashSet and TreeSet
  • Java Sorting with Comparable and Comparator
  • Java Maps: HashMap, LinkedHashMap and TreeMap
  • Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue
  • Choosing a Java Collection: Immutable and Sequenced Collections
  • Java Exception Handling: try, catch and finally
  • Java throw, throws, Checked vs Unchecked and Custom Exceptions
  • Java try-with-resources and Clean Error Handling
  • Java Generics: Type-Safe Containers
  • Java Generic Methods, Bounded Types and Wildcards
  • Java Lambdas and Functional Interfaces
  • Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
  • Java Optional: Saying Maybe Without null
  • Java Streams I: filter, map and reduce
  • Java Streams II: Collectors, groupingBy and flatMap
  • Why Concurrency: Processes, Threads and the Main Thread in Java
  • Creating Threads in Java: Thread, Runnable and Lambdas
  • Java Thread Lifecycle: sleep, join and interrupt
  • Java Race Conditions and synchronized
  • Java volatile and Atomic Variables
  • Java ExecutorService and Thread Pools
  • Java Callable, Future and CompletableFuture
  • Java Locks, Deadlock and tryLock
  • Java Concurrent Collections and Virtual Threads
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Java Files and Directories with NIO.2: Path and Files
  • Reading and Writing Text Files in Java
  • Java Structured Data: Reading and Writing JSON and CSV
  1. Blog
  2. /
  3. Java
  4. /
  5. Collections

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Collections

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)
Two rules in a row. byArtist compares Ed Sheeran with Imagine Dragons: -4, so Perfect goes first. Believer and Thunder are both Imagine Dragons: byArtist returns 0, a tie, so thenComparing asks the title rule, which returns -18, so Believer goes before Thunder. Result: Perfect, Believer, Thunder. rule 1: byArtist rule 2: title (natural order) Ed Sheeran vs Imagine Dragons: -4 Believer vs Thunder: 0, a tie "Believer" vs "Thunder": -18 Result: Perfect, Believer, Thunder only on 0
The second rule is asked only when the first one says zero.

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

ComparableComparator
Livesinside the classoutside, in its own object
MethodcompareTo(other)compare(a, b)
Ordersone, the natural orderas many as you write
Sort callCollections.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.

Keep going in Java · 51 of 79

Previous
Java Sets: HashSet, LinkedHashSet and TreeSet
Next post
Java Maps: HashMap, LinkedHashMap and TreeMap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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.

On this page

  • compareTo says who comes first
  • A song that knows its own order
  • A second order, from outside
  • A tie? Ask the next rule
  • Comparable or Comparator
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.