Implementing Comparator for Sorting Collections
Sorting Collections with Comparator
To use the Comparator
interface for sorting collections in Java, you can follow these steps:
- Implement the
Comparator
Interface: Create a new class that implements the Comparator
interface and override the compare(T o1, T o2)
method. This method should return a negative integer, zero, or a positive integer depending on whether o1
is less than, equal to, or greater than o2
.
Comparator<Person> byName = (p1, p2) -> p1.getName().compareTo(p2.getName());
Comparator<Person> byAge = (p1, p2) -> Integer.compare(p1.getAge(), p2.getAge());
- Use the Comparator in Collection Sorting Methods: Pass the
Comparator
implementation to the appropriate sorting method, such as Collections.sort()
or Arrays.sort()
.
List<Person> people = new ArrayList<>();
// Add people to the list
Collections.sort(people, byName);
Arrays.sort(people, byAge);
- Chain Multiple Comparators: You can chain multiple
Comparator
instances using the thenComparing()
method to define a more complex sorting order.
Comparator<Person> byNameAndAge = byName.thenComparing(byAge);
Collections.sort(people, byNameAndAge);
Sorting Collections with Anonymous Comparators
Alternatively, you can create an anonymous Comparator
instance directly when calling the sorting method:
Collections.sort(people, (p1, p2) -> p1.getName().compareTo(p2.getName()));
Arrays.sort(people, (p1, p2) -> Integer.compare(p1.getAge(), p2.getAge()));
This approach is useful for simple, one-time comparisons, but it can make the code less readable for more complex sorting requirements.