![]() |
VOOZH | about |
The Comparator interface in Java is used to define custom sorting logic for objects. It allows sorting collections based on different attributes without modifying the original class. It is used:
[1, 2, 5, 8]
Explanation:
public interface Comparator<T> {
int compare(T o1, T o2);
}
Compares two objects to determine their sorting order. It returns a negative, zero, or positive value based on the comparison result.
5
Syntax:
int compare(T o1, T o2)
Description:
Creates a comparator using a key extractor function, allowing objects to be sorted based on a specific field.
18 21 23
Syntax:
static <T, U extends Comparable<? super U>>
Comparator<T> comparing(Function<? super T, ? extends U> keyExtractor)
Description:
Primitive-specific comparator methods that improve performance by avoiding unnecessary boxing.
1 100 4.9 2 200 4.5
Syntax:
static <T> Comparator<T> comparingInt(
ToIntFunction<? super T> keyExtractor)static <T> Comparator<T> comparingLong(
ToLongFunction<? super T> keyExtractor)static <T> Comparator<T> comparingDouble(
ToDoubleFunction<? super T> keyExtractor)
Description:
Returns a comparator that sorts elements in the reverse order of the original comparator.
[20, 10, 5]
Syntax:
default Comparator<T> reversed()
Description:
Used for multi-level sorting by applying a secondary comparison when the primary comparison results in equality.
25 Adam 25 Bob 30 Carl
Syntax:
default Comparator<T> thenComparing(Comparator<? super T> other)
Description:
Method | Description | Example Use Case |
|---|---|---|
Comparator.naturalOrder() | Returns a comparator that sorts elements in their natural order. | Sort integers or strings in ascending order |
Comparator.reverseOrder() | Returns a comparator that reverses natural ordering. | Reverse sorting of Comparable objects |
Comparator.nullsFirst(Comparator) | Treats null values as smaller than non-null values. | Sorting lists containing null safely |
Comparator.nullsLast(Comparator) | Treats null values as greater than non-null values. | Place null values at the end |