Java 8 – Comparator.comparingLong() method

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

1. Comparator.comparingLong() method :

  • This static method accepts a function that extracts a long 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> comparingLong(ToLongFunction<? super T> keyExtractor)
  • Where
    • T is the type of element to be compared
    • keyExtractor is the function used to extract the long sort key
  • Exception :- Throws NullPointerException, if the argument is null

2. Comparator.comparingLong() examples :

2.1 Sort Product list according to their Quantity

  • 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 quantity is of type primitive long

Product.java

package net.bench.resources.comparator.comparinglong;

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
}

SortProductListByQuantity.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 Quantity using Stream‘s sorted() method passing Comparator.comparingLong() as argument
  • Comparator.comparingLong() accepts ToLongFunction which means it accepts key of long type only
package net.bench.resources.comparator.comparinglong;

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

public class SortProductListByQuantity {

	// 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); // iterate/printing



		// 2. sorting Product list in ascending-order by its Quantity
		System.out.println("\n\nSorted Product list"
				+ " in ascending-order of Quantity :-\n");


		// 2.1 sorting/iterating/printing
		products
		.stream() // 1. get sequential stream
		.sorted(Comparator.comparingLong(Product::getQuantity)) // 2. long sorting
		.forEach(System.out::println); // 3. iterate/printing
	}
}

Output:

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 Quantity :-

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

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 is of type primitive long

Student.java

package net.bench.resources.comparator.comparinglong;

public class Student {

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


	// 3-arg parameterized constructors

	// getters & setters

	// toString()
}

SortStudentListByRollNumber.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 rollNumber using Collections.sort() method passing Comparator.comparingLong() as 2nd argument and original list as 1st argument
  • Comparator.comparingLong() accepts ToLongFunction which means it accepts key of long type only
package net.bench.resources.comparator.comparinglong;

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

public class SortStudentListByRollNumber {

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

		return Arrays.asList(

				new Student(20042033L, "Viraj", 29),
				new Student(20042021L, "Rishi", 25),
				new Student(20042026L, "Aditya", 33),
				new Student(20042014L, "Krish", 19),
				new Student(20042037L, "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 "
				+ "according to Roll Number :-\n");


		// 2.1 sorting using Collections.sort() & Comparator
		Collections.sort(
				studentList, // original list
				Comparator.comparingLong(Student::getRollNumber) // long sorting
				);


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

Output:

Student list as per Insertion-order :-

Student [rollNumber=20042033, name=Viraj, age=29]
Student [rollNumber=20042021, name=Rishi, age=25]
Student [rollNumber=20042026, name=Aditya, age=33]
Student [rollNumber=20042014, name=Krish, age=19]
Student [rollNumber=20042037, name=Suresh, age=34]


Sorted Student list according to Roll Number :-

Student [rollNumber=20042014, name=Krish, age=19]
Student [rollNumber=20042021, name=Rishi, age=25]
Student [rollNumber=20042026, name=Aditya, age=33]
Student [rollNumber=20042033, name=Viraj, age=29]
Student [rollNumber=20042037, name=Suresh, age=34]

2.3 Throws NullPointerException if argument is NULL

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

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.comparingLong(null)) // 2. null
		.forEach(System.out::println); // 3. iterate/printing
	}
}

Output:

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.comparingLong(Comparator.java:509)
	at net.bench.resources.comparator.comparinglong.SortProductListWithNullPresent
.main(SortProductListWithNullPresent.java:35)

References:

Happy Coding !!
Happy Learning !!

Java 8 – Comparator.comparingDouble() method
Java 8 – Comparator.comparingInt() method