Comparator
Compares two values for the purpose of ordering.
Used for ordering (sorting or maintaining the sorted order of) items in an array or Collection
, or sorting the items flowing through a Stream
.
A Comparator
<T>
is typically used when a natural ordering is not defined (i.e. when T
does not implement Comparable
<T>
), or as an alternative to natural order.
The method to be implemented is int compare(T t1, T t2)
. A lambda implementation must therefore take 2 parameters of type T
, and return an int
, where a negative value implies that t1 < t2
(for the purpose of ordering), a positive value implies t1 > t2
, and zero means that t1
and t2
are equivalent for ordering purposes.
An implementation can (and generally should) take advantage of comparison capabilities defined for the types that make up the state of T
, as well as the static factory methods provided by Comparator
.
Arrays.sort(T[],
Comparator
)
:Integer[] data = {-1, 3, 2, 10, -5, 6};
Arrays.sort(data, (d1, d2) -> Double.compare(1.0 / d1, 1.0 / d2));
System.out.println(Arrays.toString(data));
List
by reciprocal values using List
.sort(
Comparator
)
:List<Integer> data = new LinkedList<>(List.of(-1, 3, 2, 10, -5, 6));
data.sort((d1, d2) -> Double.compare(1.0 / d1, 1.0 / d2));
System.out.println(data);
Stream
by reciprocal values using Stream
.sorted(
Comparator
)
:System.out.println(Stream.of(-1, 3, 2, 10, -5, 6)
.sorted((d1, d2) -> Double.compare(1.0 / d1, 1.0 / d2))
.collect(Collectors.toList()));
All of the above produce the same output:
[-1, -5, 10, 6, 3, 2]