0
0
JavaHow-ToBeginner · 3 min read

How to Use Custom Comparator in Java: Syntax and Example

In Java, you use a Comparator interface to define a custom comparison logic by overriding its compare() method. This custom comparator can then be passed to sorting methods like Collections.sort() or Arrays.sort() to sort objects based on your rules.
📐

Syntax

The Comparator interface requires implementing the compare(T o1, T o2) method, which returns a negative number if o1 should come before o2, zero if they are equal, or a positive number if o1 should come after o2.

You can create a custom comparator by implementing this interface in a class or using a lambda expression.

java
Comparator<Type> comparator = new Comparator<Type>() {
    @Override
    public int compare(Type o1, Type o2) {
        // custom comparison logic
        return 0; // replace with actual comparison logic
    }
};
💻

Example

This example shows how to sort a list of strings by their length using a custom comparator implemented with a lambda expression.

java
import java.util.*;

public class CustomComparatorExample {
    public static void main(String[] args) {
        List<String> fruits = Arrays.asList("apple", "banana", "kiwi", "orange");

        // Custom comparator to sort by string length
        Comparator<String> lengthComparator = (s1, s2) -> Integer.compare(s1.length(), s2.length());

        Collections.sort(fruits, lengthComparator);

        System.out.println(fruits);
    }
}
Output
[kiwi, apple, banana, orange]
⚠️

Common Pitfalls

  • Returning incorrect values in compare() can cause wrong sorting order or runtime errors.
  • Not handling null values can cause NullPointerException.
  • Using subtraction for comparison (e.g., s1.length() - s2.length()) can overflow for large numbers; use Integer.compare() instead.
java
import java.util.*;

public class ComparatorPitfall {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1000000000, 2000000000, -1000000000);

        // Wrong: subtraction can overflow
        Comparator<Integer> wrongComparator = (a, b) -> a - b;

        // Right: use Integer.compare to avoid overflow
        Comparator<Integer> rightComparator = (a, b) -> Integer.compare(a, b);

        Collections.sort(numbers, rightComparator);
        System.out.println(numbers);
    }
}
Output
[-1000000000, 1000000000, 2000000000]
📊

Quick Reference

Comparator Interface Key Points:

  • compare(T o1, T o2): returns negative, zero, or positive int.
  • Use lambda expressions for concise syntax.
  • Pass comparator to Collections.sort() or Arrays.sort().
  • Handle null values carefully.
  • Use Integer.compare() or similar methods to avoid overflow.

Key Takeaways

Implement the Comparator interface and override compare() to define custom sorting logic.
Use lambda expressions for simpler and cleaner comparator code.
Avoid subtraction in compare() to prevent integer overflow; use Integer.compare() instead.
Always consider null values to avoid runtime exceptions.
Pass your custom comparator to sorting methods like Collections.sort() to control order.