Arrays.sort with a Comparator
You'll learn how to sort object arrays using custom logic by providing a Comparator.
The Core Idea
When you used Arrays.sort() on object arrays, Java sorted them using their "natural order" (the order defined by the objects' compareTo method). But what if you want to sort strings by length instead of alphabetically? Or sort people by age instead of name? That's where a Comparator comes in—it's an object that defines custom comparison logic.
Think of a Comparator like a referee who decides which of two contestants wins. Instead of using default rules, you give the referee your own instructions: "Compare by height," "Compare by speed," or any criteria you choose.
How It Works
The Arrays.sort() method has an overloaded version that accepts a Comparator as a second parameter:
Arrays.sort(arrayName, comparator);
The Comparator's job is to compare two objects and return:
- A negative number if the first should come before the second
- Zero if they're equal
- A positive number if the first should come after the second
Example: Sorting Strings by Length
import java.util.Arrays;
import java.util.Comparator;
String[] words = {"elephant", "cat", "butterfly", "dog"};
Comparator<String> byLength = new Comparator<String>() {
public int compare(String s1, String s2) {
return s1.length() - s2.length();
}
};
Arrays.sort(words, byLength);
System.out.println(Arrays.toString(words));
// Output: [cat, dog, elephant, butterfly]
Notice how the array is now sorted by word length, not alphabetically!
Key Takeaway: Use Arrays.sort(array, comparator) to define custom sorting logic for object arrays by providing a Comparator that specifies how to compare two elements.