Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING INTRO TO HTML & CSS BASH RUST TOOLS

Java Tutorial

Java HOME Java Intro Java Get Started Java Syntax Java Output Java Comments Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Math Java Booleans Java If...Else Java Switch Java While Loop Java For Loop Java Break/Continue Java Arrays

Java Methods

Java Methods Java Method Challenge Java Method Parameters Java Method Overloading Java Scope Java Recursion

Java Classes

Java OOP Java Classes/Objects Java Class Attributes Java Class Methods Java Class Challenge Java Constructors Java this Keyword Java Modifiers Java Encapsulation Java Packages / API Java Inheritance Java Polymorphism Java super Keyword Java Inner Classes Java Abstraction Java Interface Java Anonymous Java OOP Visuals Java Enum Java User Input Java Date

Java Errors

Java Errors Java Debugging Java Exceptions Java Multiple Exceptions Java try-with-resources

Java Problem Solving

Java Problem Solving Java Build the Logic Java Test Cases

Java File Handling

Java Files Java Create Files Java Write Files Java Read Files Java Delete Files

Java I/O Streams

Java I/O Streams Java FileInputStream Java FileOutputStream Java BufferedReader Java BufferedWriter

Java Data Structures

Java Data Structures Java Collections Java List Java ArrayList Java LinkedList Java List Sorting Java Set Java HashSet Java TreeSet Java LinkedHashSet Java Map Java HashMap Java TreeMap Java LinkedHashMap Java Iterator Java Algorithms

Java Advanced

Java Wrapper Classes Java Generics Java Annotations Java RegEx Java Threads Java Lambda Java Optional Java Advanced Sorting

Java Projects

Java Projects

Java Cert

Java Certificate

Java How To's

Java How Tos

Java Examples

Java Examples Java Videos Java Compiler Java Exercises Java Quiz Java Code Challenges Java Practice Problems Java Server Java Syllabus Java Study Plan Java Interview Q&A

Java Reference

Java Reference Java Keywords ArrayList Methods Arrays Methods BufferedReader BufferedWriter Character Methods Collections Methods Comparator Methods Date and Time Enum Methods Errors & Exceptions File Methods FileInputStream FileOutputStream FileReader FileWriter HashMap Methods HashSet Methods Integer Methods Iterator Methods LinkedHashMap Methods LinkedHashSet Methods LinkedList Methods Math Methods Optional Methods Output Methods Random Methods RegEx Methods Scanner Methods String Methods StringBuilder Methods System Methods Thread Methods TreeMap Methods TreeSet Methods


Java Comparator thenComparing() Method

❮ Comparator Methods


Example

Sort cars by brand, and cars with the same brand by year:

import java.util.ArrayList;
import java.util.Comparator;

public class Main {
  static class Car {
    String brand;
    int year;
    Car(String brand, int year) {
      this.brand = brand;
      this.year = year;
    }
    public String toString() {
      return brand + " " + year;
    }
  }

  public static void main(String[] args) {
    Comparator<Car> byBrand = Comparator.comparing(c -> c.brand);
    ArrayList<Car> myCars = new ArrayList<Car>();
    myCars.add(new Car("Ford", 2006));
    myCars.add(new Car("BMW", 1999));
    myCars.add(new Car("Ford", 1970));
    myCars.sort(byBrand.thenComparing(c -> c.year));
    System.out.println(myCars);
  }
}

Try it Yourself »


Share

Definition and Usage

The thenComparing() method returns a new comparator with a second sorting rule. The second rule is only used when the first rule finds two objects equal (when it returns 0).

For example, sort cars by brand, and when two cars have the same brand, sort them by year.

Tip: You can call thenComparing() more than once, to add a third or a fourth rule.


Syntax

One of the following:

public Comparator<T> thenComparing(Comparator<? super T> other)
public <U extends Comparable<? super U>> Comparator<T> thenComparing(Function<? super T, ? extends U> keyExtractor)
public <U> Comparator<T> thenComparing(Function<? super T, ? extends U> keyExtractor, Comparator<? super U> keyComparator)

T refers to the data type of the objects to sort, for example Car. U refers to the data type of the key (the value that is compared), for example String.

Parameter Values

Parameter Description
other A comparator to use when the first comparator finds two objects equal. Use either other or keyExtractor.
keyExtractor A Function or lambda expression that returns the value to sort by when the first comparator finds two objects equal, for example c -> c.year.
keyComparator Optional. A comparator that compares the keys from keyExtractor. If it is left out, the keys are compared in their natural order.

Technical Details

Returns: A Comparator that uses this comparator first, and the second rule when two objects are equal.

Related Pages

Java Advanced Sorting Tutorial

Java List Sorting Tutorial

Java Lambda Expressions Tutorial


❮ Comparator Methods

Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.