Java 8 – Comparator.thenComparingInt() method

In this article, we will discuss how to sort list of Objects on multiple field/parameters using static method Comparator.comparing() and default method thenComparingInt()

  • Comparing.comparing() method is used to sort any type of key for 1st level sorting
  • thenComparingInt() accepts ToIntFunction functional interface which means it is used to sort integer-type key for 2nd level sorting

1. thenComparingInt() method :

  • Returns a lexicographic-order comparator with a function that extracts an int sort key
  • This default method accepts a function that extracts an int sort key from a type T
  • Method signature :-
    • default Comparator<T> thenComparingInt(ToIntFunction<? super T> keyExtractor)
  • Where
    • T is the type of element to be compared
    • keyExtractor is the function used to extract the integer sort key
  • Exception :- Throws NullPointerException, if the argument is null
  • Check Java doc

2. thenComparingInt() examples :

2.1 Sort Product list first by Name & then by Id

  • Product class is defined with 4 attributes namely id, name, quantity and their price
  • Along with 4 attributes, parameterized constructor, getters/setters and toString() method is defined – removed for brevity
  • Member variable id is of type primitive int

Product.java

package net.bench.resources.comparator.thencomparingint;

public class Product {

	// member variables
	private int id;
	private String name;
	private long quantity;
	private double price;

	// 4-arg parameterized constructor

	// getters and setters

	// toString() method
}

SortProductListByNameAndThenById.java

  • A list contains Product information for 5 as per insertion-order with some product names are same
  • 2-level attribute Sorting :-
    • Comparator.comparing() :- we are going to sort the Product list according to alphabetial order of its name for the 1st level sorting
    • thenComparingInt() :- then we are going to compare their Ids, if name of the Products are same for 2nd level sorting
  • thenComparingInt() method accepts ToIntFunction which means it accepts key of integer type only
package net.bench.resources.comparator.thencomparingint;

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

import net.bench.resources.comparator.thencomparing.Product;

public class SortProductListByNameAndThenById {

	// List of Products
	private static List<Product> getProductList() {

		return Arrays.asList(
				new Product(101, "Wheat", 1089L, 36.89),
				new Product(102, "Oil", 502L, 58.19),
				new Product(103, "Lentils", 803L, 102.45),
				new Product(104, "Wheat", 208L, 164.75),
				new Product(105, "Oil", 303L, 45.50)
				);
	}

	public static void main(String[] args) {

		// 1. get Product list
		List<Product> products = getProductList();


		// 1.1 print to console
		System.out.println("Product list as per Insertion-order :-\n");
		products.forEach(System.out::println); // iterating/printing



		// 2. Sort Product list first by Name & then by Id
		System.out.println("\n\nSort Product list first by Name & then by Id :-\n");


		// 2.1 sorting/iterating/printing
		products
		.stream() // 1. get sequential stream
		.sorted(
				Comparator.comparing(Product::getName) // 1. name sorting
				.thenComparingInt(Product::getId) // 2. Id sorting
				)
		.forEach(System.out::println); // 3. iterate/printing
	}
}

Output:

Product list as per Insertion-order :-

Product [name=Wheat, id=101, quantity=1089, price=36.89]
Product [name=Oil, id=102, quantity=502, price=58.19]
Product [name=Lentils, id=103, quantity=803, price=102.45]
Product [name=Wheat, id=104, quantity=208, price=164.75]
Product [name=Oil, id=105, quantity=303, price=45.5]


Sort Product list first by Name & then by Id :-

Product [name=Lentils, id=103, quantity=803, price=102.45]
Product [name=Oil, id=102, quantity=502, price=58.19]
Product [name=Oil, id=105, quantity=303, price=45.5]
Product [name=Wheat, id=101, quantity=1089, price=36.89]
Product [name=Wheat, id=104, quantity=208, price=164.75]

2.2 Sort Student list first by Name & then by Age

  • Student class is defined with 3 attributes namely id, name and their age
  • Along with 3 attributes, parameterized constructor, getters/setters and toString() method is defined – removed for brevity
  • Member variable id and age is of type primitive int

Student.java

package net.bench.resources.comparator.thencomparingint;

public class Student {

	// member variables
	private int rollNumber;
	private String name;
	private int age;

	// 3-arg parameterized constructors

	// getters & setters

	// toString()
}

SortStudentListByNameAndThenByAge.java

  • A list contains Student information for 5 as per insertion-order with few students having same names
  • 2-level attribute Sorting :-
    • Comparator.comparing() :- we are going to sort the Student list according to alphabetial order of its name for the 1st level sorting
    • thenComparingInt() :- then we are going to compare their ages, if name of the Students are same for 2nd level sorting
  • thenComparingInt() method accepts ToIntFunction which means it accepts key of integer type only
package net.bench.resources.comparator.thencomparingint;

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

public class SortStudentListByNameAndThenByAge {

	// List of Students
	private static List<Student> getStudentList() {

		return Arrays.asList(
				new Student(2033, "Viraj", 29),
				new Student(2020, "Krish", 25),
				new Student(2004, "Aditya", 33),
				new Student(2015, "Krish", 19),
				new Student(2037, "Viraj", 34)
				);
	}

	public static void main(String[] args) {

		// 1. get Student list
		List<Student> studentList = getStudentList();


		// 1.1 print to console
		System.out.println("Student list as per Insertion-order :-\n");
		studentList.forEach(System.out::println); // iterate/printing



		// 2. Sort Student list first by Name & then by Age
		System.out.println("\n\nSort Student list first by Name & then by Age :-\n");


		// 2.1 sorting using Collections.sort() & Comparator
		Collections.sort(studentList, // original list
				Comparator.comparing(Student::getName) // 1. name sorting
				.thenComparingInt(Student::getRollNumber) // 2. age sorting
				);


		// 2.2 print to console
		studentList.forEach(System.out::println); // iterate/printing
	}
}

Output:

Student list as per Insertion-order :-

Student [rollNumber=2033, name=Viraj, age=29]
Student [rollNumber=2020, name=Krish, age=25]
Student [rollNumber=2004, name=Aditya, age=33]
Student [rollNumber=2015, name=Krish, age=19]
Student [rollNumber=2037, name=Viraj, age=34]


Sort Student list first by Name & then by Age :-

Student [rollNumber=2004, name=Aditya, age=33]
Student [rollNumber=2015, name=Krish, age=19]
Student [rollNumber=2020, name=Krish, age=25]
Student [rollNumber=2033, name=Viraj, age=29]
Student [rollNumber=2037, name=Viraj, age=34]

2.3 Throws NullPointerException if argument is NULL

  • If the input argument to thenComparingInt() method is null then it throws NullPointerException as shown in the below illustration
  • Check How to sort List and Arrays with null values to handle list with null values while sorting

SortProductListWithNullPresent.java

package net.bench.resources.comparator.thencomparingint;

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

import net.bench.resources.comparator.thencomparing.Product;

public class SortProductListWithNullPresent {

	// List of Products
	private static List<Product> getProductList() {

		return Arrays.asList(
				null,
				new Product(102, "Rice", 502L, 58.19),
				new Product(104, "Oil", 208L, 164.75),
				new Product(103, "Lentils", 803L, 102.45),
				new Product(105, "Vegetables", 303L, 45.50),
				new Product(101, "Wheat", 1089L, 36.89)
				);
	}

	public static void main(String[] args) {

		// 1. get Product list
		List<Product> products = getProductList();


		// 1.1 print to console
		System.out.println("Product list as per Insertion-order :-\n");
		products.forEach(System.out::println); // iterating/printing



		// 2. Sort Product list first by Name & then by Id
		System.out.println("\n\nSort Product list first by Name & then by Id :-\n");


		// 2.1 sorting/iterating/printing
		products
		.stream() // 1. get sequential stream
		.sorted(
				Comparator.comparing(Product::getName) // 1. name sorting
				.thenComparingInt(Product::getId) // 2. Id sorting
				) // 2. alphabetical name
		.forEach(System.out::println); // 3. iterate/printing
	}
}

Output:

Product list as per Insertion-order :-

null
Product [name=Rice, id=102, quantity=502, price=58.19]
Product [name=Oil, id=104, quantity=208, price=164.75]
Product [name=Lentils, id=103, quantity=803, price=102.45]
Product [name=Vegetables, id=105, quantity=303, price=45.5]
Product [name=Wheat, id=101, quantity=1089, price=36.89]


Sort Product list first by Name & then by Id :-

Exception in thread "main" java.lang.NullPointerException
	at java.util.Comparator.lambda$comparing$77a9974f$1(Comparator.java:469)
	at java.util.Comparator.lambda$thenComparing$36697e65$1(Comparator.java:216)
	at java.util.TimSort.countRunAndMakeAscending(TimSort.java:355)
	at java.util.TimSort.sort(TimSort.java:220)
	at java.util.Arrays.sort(Arrays.java:1512)
	at java.util.stream.SortedOps$SizedRefSortingSink.end(SortedOps.java:348)
	at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:482)
	at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
	at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151)
	at java.util.stream.ForEachOps$ForEachOp$OfRef
.evaluateSequential(ForEachOps.java:174)
	at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
	at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)
	at net.bench.resources.comparator.thencomparingint.SortProductListWithNullPresent
.main(SortProductListWithNullPresent.java:47)

References:

Happy Coding !!
Happy Learning !!

Java 8 – Comparator.thenComparingLong() method
Java 8 – thenComparing() method for custom/reverse sorting