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;
public static<T> Comparator<T> comparingDouble(ToDoubleFunction<? super T> keyExtractor)
ToDoubleFunction<? super T> keyExtractor
: The function that is used to extract the sort key.This method returns a Comparator
.
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);}}
Person
class with age
as the attribute.Person
objects with different ages.Person
objects that were created.Person
objects that were created before sorting.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.Person
objects after sorting.