Package relations: + java.util + - java.lang.Comparator<T>
Parameter type:
T
- the type of objects that may be compared by this comparator
This is a functional interface.
The Comparator
is a functional interface that used to define a custom ordering for objects. This interface is useful for sorting a collection of objects that is different from their natural ordering, or when objects do not have a natural ordering using collections sort.
The Comparator
interface has a single abstract method compare()
and several default methods.
Difference between Comparable and Comparator
compare()
The compare()
is an abstract method that compares two arguments for order.
This method returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
Implement with anonymous nested class
You can implement the Comparator
interface and override the compare()
method using anonymous nested class.
[[Name: Tim, Age: 12], [Name: Jason, Age: 23], [Name: John, Age: 31]]
Implement with lambda expression
The below is the implementation of the Comparator
interface using lambda expression.
[[Name: Tim, Age: 12], [Name: Jason, Age: 23], [Name: John, Age: 31]]
We can also use the static method comparingInt()
that comes with the Comparator
interface to replace the compare() method from Integer
class.
The comparingInt()
takes a function (or lambda expression) that extracts an int
from a Person
object. In this case, the lambda (Person o) -> o.age
extracts the age
, and it returns a Comparator
that compares by the age
value.
Comparator default methods
Method | Description |
---|---|
static <T> Comparator<T> comparingInt(ToIntFunction<? super T> keyExtractor) | It accepts a function that extracts an int sort key from a type T, and returns a Comparator that compares by that sort key |
static <T> Comparator<T> comparingDouble(ToDoubleFunction<? super T> keyExtractor) | It accepts a function that extracts a double sort key from a type T, and returns a Comparator that compares by that sort key |
Back to parent page: Java Standard Edition (Java SE) and Java Programming
Web_and_App_DevelopmentProgramming_LanguagesJavaComparatorLambda_ExpressionAnonymous_Nested_Class