Java Collections - Comparator.thenComparingInt() Examples

Java Collections Java Java API 





default Comparator<T> thenComparingInt(ToIntFunction<? super T> keyExtractor)

This default method returns a comparator chained with this comparator. The returned comparator uses the specified function to extract the Comparable int sort key.


package com.logicbig.example.comparator;

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

public class ThenComparingIntExample {

public static void main(String... args) {
List<Item> list = createExampleItems();
System.out.printf("before sort: %s%n", list);
Collections.sort(list, Comparator.comparing(Item::getName)
System.out.printf("after sort: %s%n", list);

private static List<Item> createExampleItems() {
return Arrays.asList(
new Item("Laptop", 1000),
new Item("Desktop", 900),
new Item("Laptop", 1200),
new Item("Monitor", 400),
new Item("Desktop", 1100)

private static class Item {
private String name;
private int price;

public Item(String name, int price) { = name;
this.price = price;

public String getName() {
return name;

public int getPrice() {
return price;

public String toString() {
return name + "-" + price;


before sort: [Laptop-1000, Desktop-900, Laptop-1200, Monitor-400, Desktop-1100]
after sort: [Desktop-900, Desktop-1100, Laptop-1000, Laptop-1200, Monitor-400]

See Also