What is the Comparator.comparingDouble() method in Java?

Overview

comparingDouble() is a static method of the Comparator class that is used to return a Comparator that sorts elements. comparingDouble() sorts elements using a double type sort key that is extracted with the help of the implementation of the ToDoubleFunction functional interface. This interface is passed to the method as a parameter.

The Comparator interface is defined in the java.util package. To import the Comparator interface, we use the following import statement:

import java.util.Comparator;

Syntax

public static<T> Comparator<T> comparingDouble(ToDoubleFunction<? super T> keyExtractor)

Parameters

  • ToDoubleFunction<? super T> keyExtractor: The function that is used to extract the sort key.

Return value

This method returns a Comparator.

Code

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class Main{
static class Person{
double age;
public Person(double age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"age=" + age +
'}';
}
}
public static void main(String[] args) {
Person person1 = new Person(14.5);
Person person3 = new Person(43.2);
Person person2 = new Person(92.1);
List<Person> personList = Arrays.asList(person1, person2, person3);
System.out.println("Before sorting: " + personList);
personList.sort(Comparator.comparingDouble(value -> value.age));
System.out.println("After sorting: " + personList);
}
}

Code explanation

  • Lines 1–3: We import the relevant packages.
  • Line 7: We define a Person class with age as the attribute.
  • Lines 23–25: We create different Person objects with different ages.
  • Line 26: We create a list of the Person objects that were created.
  • Line 27: We print the list of Person objects that were created before sorting.
  • Line 28: We use the comparingDouble() method, where we create an implementation of the ToDoubleFunction interface, to sort the list. This interface extracts the age attribute from the Person objects.
  • Line 29: We print the list of Person objects after sorting.

Free Resources