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;}@Overridepublic 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
Personclass withageas the attribute. - Lines 23–25: We create different
Personobjects with different ages. - Line 26: We create a list of the
Personobjects that were created. - Line 27: We print the list of
Personobjects that were created before sorting. - Line 28: We use the
comparingDouble()method, where we create an implementation of theToDoubleFunctioninterface, to sort the list. This interface extracts theageattribute from thePersonobjects. - Line 29: We print the list of
Personobjects after sorting.