Java Comparator compare() Method
Example
Create a comparator that compares strings by their length, and call its compare() method:
import java.util.Comparator;
public class Main {
public static void main(String[] args) {
Comparator<String> byLength = (a, b) -> a.length() - b.length();
System.out.println(byLength.compare("BMW", "Volvo"));
System.out.println(byLength.compare("Mazda", "Ford"));
System.out.println(byLength.compare("Volvo", "Mazda"));
}
}
Definition and Usage
The compare() method compares two objects to decide which one should come first. It is the method that you write when you create a comparator, in a class that implements Comparator or with a lambda expression (a short block of code that works like a method).
It returns a negative number if the first object should come first, a positive number if the second object should come first, and 0 if the order does not matter. Sorting methods, like list.sort() and Collections.sort(), call compare() for you.
Tip: Pass the comparator to a sorting method to use it, for example cars.sort(byLength);.
Syntax
public int compare(T o1, T o2)
T refers to the data type of the objects to compare, for example Car or String.
Parameter Values
| Parameter | Description |
|---|---|
| o1 | Required. The first object to compare. |
| o2 | Required. The second object to compare. |
Technical Details
| Returns: | An int: a negative number if o1 should come first, a positive number if o2 should come first, and 0 if the order does not matter. |
|---|
Related Pages
Java Advanced Sorting Tutorial
Java Lambda Expressions Tutorial
❮ Comparator Methods