Comparator Interface

About

The Comparator<T> @FunctionalInterface interface in Java is part of the java.util package and is used to define custom sorting logic for objects. Unlike Comparable<T>, which imposes a natural ordering within a class, Comparator<T> allows sorting logic to be defined externally.

Key Features of Comparator

  • Enables custom sorting for objects.

  • Can be used to sort objects based on multiple fields.

  • Provides various default methods (since Java 8) for enhanced functionality.

  • Supports method references and lambda expressions for concise syntax.

Abstract Methods

int compare(T o1, T o2)

This is the only abstract method in Comparator. It must be implemented to define custom comparison logic.

Compares two objects and returns: - Negative if o1 < o2 - Zero if o1 == o2 - Positive if o1 > o2

Comparator<Integer> intComparator = (a, b) -> Integer.compare(a, b);
System.out.println(intComparator.compare(10, 20)); // Output: -1
import java.util.*;

public class ComparatorExample {
    public static void main(String[] args) {
        Comparator<Integer> intComparator = new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1 - o2; // Ascending order comparison
            }
        };

        List<Integer> numbers = Arrays.asList(5, 2, 8, 1);
        Collections.sort(numbers, intComparator);

        // Output: [1, 2, 5, 8]
        System.out.println(numbers);
    }
}

Default Methods

Method
Description

Comparator<T> reversed();

Returns a comparator that reverses the order of comparison.

Comparator<T> thenComparing(Comparator<? super T> other);

Allows chaining multiple comparison criteria.

<U> Comparator<T> thenComparing(Function<? super T, ? extends U> keyExtractor, Comparator<? super U> keyComparator);

Sorts using a key extracted from the object.

<U extends Comparable<? super U>> Comparator<T> thenComparing(Function<? super T, ? extends U> keyExtractor);

Sorts using a Comparable key extracted from the object.

Comparator<T> thenComparingInt(ToIntFunction<? super T> keyExtractor);

Sorts based on an int key.

Comparator<T> thenComparingLong(ToLongFunction<? super T> keyExtractor);

Sorts based on a long key.

Comparator<T> thenComparingDouble(ToDoubleFunction<? super T> keyExtractor);

Sorts based on a double key.

Static Methods

Java 8 introduced several static methods for creating comparators.

Method
Description

Comparator<T> naturalOrder();

Returns a comparator based on natural ordering (assumes T implements Comparable<T>).

Comparator<T> reverseOrder();

Returns a comparator that reverses natural ordering.

<T, U extends Comparable<? super U>> Comparator<T> comparing(Function<? super T, ? extends U> keyExtractor);

Compares using a key extracted from the object.

<T, U> Comparator<T> comparing(Function<? super T, ? extends U> keyExtractor, Comparator<? super U> keyComparator);

Compares using a key with a custom comparator.

<T> Comparator<T> comparingInt(ToIntFunction<? super T> keyExtractor);

Compares objects using an integer key.

<T> Comparator<T> comparingLong(ToLongFunction<? super T> keyExtractor);

Compares objects using a long key.

<T> Comparator<T> comparingDouble(ToDoubleFunction<? super T> keyExtractor);

Compares objects using a double key.

Utility Methods in Map.Entry

The Map.Entry class provides useful comparators for sorting maps.

Method
Description

static <K, V extends Comparable<? super V>> Comparator<Map.Entry<K, V>> comparingByValue();

Returns a comparator that compares Map.Entry objects by value.

static <K, V> Comparator<Map.Entry<K, V>> comparingByValue(Comparator<? super V> cmp);

Compares Map.Entry objects by value using a custom comparator.

static <K extends Comparable<? super K>, V> Comparator<Map.Entry<K, V>> comparingByKey();

Compares Map.Entry objects by key.

static <K, V> Comparator<Map.Entry<K, V>> comparingByKey(Comparator<? super K> cmp);

Compares Map.Entry objects by key using a custom comparator.

Last updated