Java 8 – Comparator.comparingInt() method

In this article, we will discuss how to sort list of Objects on the basis of specific integer parameter/field using Java 8 Comparator’s static method comparingInt() which accepts ToIntFunction functional interface

1. Comparator.comparingInt() method :

  • This static method accepts a function that extracts an int sort key from a type T
  • Returns a Comparator that compares by that sort key
  • The returned comparator is serializable if the specified function is also serializable
  • Method signature :-
    • static <T> Comparator<T> comparingInt(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

2. Comparator.comparingInt() examples :

2.1 Sort Product list according to their 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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package net.bench.resources.comparator.comparingint;
 
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
}

SortProductListById.java

  • A list contains Product information for 5 as per insertion-order
  • Sorting :- we are going to sort the Product list in the ascending order of Product Id using Stream‘s sorted() method passing Comparator.comparingInt() as argument
  • Comparator.comparingInt() accepts ToIntFunction which means it accepts key of integer type only
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package net.bench.resources.comparator.comparingint;
 
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
 
public class SortProductListById {
 
    // List of Products
    private static List<Product> getProductList() {
 
        return Arrays.asList(
 
                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. sorting Product list in ascending-order by its Id
        System.out.println("\n\nSorted Product list in ascending-order of Id :-\n");
 
 
        // 2.1 sorting/iterating/printing
        products
        .stream() // 1. get sequential stream
        .sorted(Comparator.comparingInt(Product::getId)) // 2. integer sorting
        .forEach(System.out::println); // 3. iterate/printing
    }
}

Output:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Product list as per Insertion-order :-
 
Product [id=102, name=Rice, quantity=502, price=58.19]
Product [id=104, name=Oil, quantity=208, price=164.75]
Product [id=103, name=Lentils, quantity=803, price=102.45]
Product [id=105, name=Vegetables, quantity=303, price=45.5]
Product [id=101, name=Wheat, quantity=1089, price=36.89]
 
 
Sorted Product list in ascending-order of Id :-
 
Product [id=101, name=Wheat, quantity=1089, price=36.89]
Product [id=102, name=Rice, quantity=502, price=58.19]
Product [id=103, name=Lentils, quantity=803, price=102.45]
Product [id=104, name=Oil, quantity=208, price=164.75]
Product [id=105, name=Vegetables, quantity=303, price=45.5]

2.2 Sort Student list according to their Age

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

Student.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package net.bench.resources.comparator.comparingint;
 
public class Student {
 
    // member variables
    private int rollNumber;
    private String name;
    private int age;
 
    // 3-arg parameterized constructors
 
    // getters & setters
 
    // toString()
}

SortStudentListByAge.java

  • A list contains 5 Student information as per insertion-order
  • Sorting :- we are going to sort the Student list in the ascending order of their age using Collections.sort() method passing Comparator.comparingInt() as 2nd argument and original list as 1st argument
  • Comparator.comparingInt() accepts ToIntFunction which means it accepts key of integer type only
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package net.bench.resources.comparator.comparingint;
 
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
 
public class SortStudentListByAge {
 
    // List of Students
    private static List<Student> getStudentList() {
 
        return Arrays.asList(
 
                new Student(2033, "Viraj", 29),
                new Student(2020, "Rishi", 25),
                new Student(2004, "Aditya", 33),
                new Student(2015, "Krish", 19),
                new Student(2037, "Suresh", 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); // iterating/printing
 
 
 
        // 2. sorting Student list in ascending-order of their Age
        System.out.println("\n\nSorted Student list by their Age :-\n");
 
 
        // 2.1 sorting using Collections.sort() & Comparator
        Collections.sort(
                studentList, // original list
                Comparator.comparingInt(Student::getAge) //integer sorting
                );
 
 
        // 2.2 print to console
        studentList.forEach(System.out::println); // iterate/printing
    }
}

Output:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Student list as per Insertion-order :-
 
Student [rollNumber=2033, name=Viraj, age=29]
Student [rollNumber=2020, name=Rishi, age=25]
Student [rollNumber=2004, name=Aditya, age=33]
Student [rollNumber=2015, name=Krish, age=19]
Student [rollNumber=2037, name=Suresh, age=34]
 
 
Sorted Student list by their Age :-
 
Student [rollNumber=2015, name=Krish, age=19]
Student [rollNumber=2020, name=Rishi, age=25]
Student [rollNumber=2033, name=Viraj, age=29]
Student [rollNumber=2004, name=Aditya, age=33]
Student [rollNumber=2037, name=Suresh, age=34]

2.3 Throws NullPointerException if argument is NULL

  • If the input argument to Comparator.comparingInt() 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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package net.bench.resources.comparator.comparingint;
 
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
 
public class SortProductListWithNullPresent {
 
    // List of Products
    private static List<Product> getProductList() {
 
        return Arrays.asList(
 
                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();
 
 
        // 2. sorting Product list in ascending-order by its Id
        System.out.println("Exception - Sorted Product list with Null value :-\n");
 
 
        // 3. sorting/iterating/printing
        products
        .stream() // 1. get sequential stream
        .sorted(Comparator.comparingInt(null)) // 2. null
        .forEach(System.out::println); // 3. iterate/printing
    }
}

Output:

1
2
3
4
5
6
7
Exception - Sorted Product list with Null value :-
 
Exception in thread "main" java.lang.NullPointerException
    at java.util.Objects.requireNonNull(Objects.java:203)
    at java.util.Comparator.comparingInt(Comparator.java:488)
    at net.bench.resources.comparator.comparingint.SortProductListWithNullPresent
.main(SortProductListWithNullPresent.java:35)

References:

Happy Coding !!
Happy Learning !!

Java 8 – Comparator.comparingLong() method
Java 8 – Comparator.comparing() method for custom/reverse sorting