How to Use Comparator in Java: Syntax and Examples
In Java,
Comparator is used to define custom order for sorting objects by implementing the compare() method. You can use it with collections like List to sort objects based on any property or logic.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, and a positive number if o1 should come after o2.
You can create a Comparator by implementing it in a class or using a lambda expression for simplicity.
java
Comparator<Type> comparator = new Comparator<Type>() { @Override public int compare(Type o1, Type o2) { // return negative if o1 < o2, zero if equal, positive if o1 > o2 return 0; // example placeholder } }; // Or using lambda (Java 8+) Comparator<Type> comparator = (o1, o2) -> { // comparison logic return 0; // example placeholder };
Example
This example shows how to sort a list of strings by their length using a Comparator with a lambda expression.
java
import java.util.*; public class ComparatorExample { public static void main(String[] args) { List<String> fruits = new ArrayList<>(Arrays.asList("apple", "banana", "kiwi", "orange")); // Sort by length using Comparator fruits.sort((s1, s2) -> s1.length() - s2.length()); System.out.println(fruits); } }
Output
[kiwi, apple, banana, orange]
Common Pitfalls
- Returning incorrect values in
compare()can cause wrong sorting order. - Subtracting integers directly can cause overflow; use
Integer.compare()for safety. - Not handling
nullvalues can causeNullPointerException.
java
import java.util.*; public class ComparatorPitfall { public static void main(String[] args) { List<Integer> numbers = new ArrayList<>(Arrays.asList(2, 5, 1, 10)); // Wrong: subtraction can overflow // numbers.sort((a, b) -> a - b); // risky // Right: use Integer.compare numbers.sort((a, b) -> Integer.compare(a, b)); System.out.println(numbers); } }
Output
[1, 2, 5, 10]
Quick Reference
| Concept | Description |
|---|---|
| Comparator Interface | Defines custom order by implementing compare(T o1, T o2) |
| compare() Return Values | Negative if o1 < o2, zero if equal, positive if o1 > o2 |
| Lambda Usage | Simplifies Comparator creation with (o1, o2) -> logic |
| Sorting Collections | Use list.sort(comparator) or Collections.sort(list, comparator) |
| Avoid Subtraction | Use Integer.compare() to prevent overflow in compare() |
Key Takeaways
Use Comparator to define custom sorting logic by implementing compare() method.
Prefer lambda expressions for concise Comparator code in Java 8 and above.
Avoid direct subtraction in compare() to prevent integer overflow; use Integer.compare().
Always handle null values if your data can contain them to avoid exceptions.
Use list.sort(comparator) or Collections.sort(list, comparator) to sort collections.