Sometimes we’ll want to sort a collection by something other than its natural order. For example, suppose we wanted to sort strings by their length instead of alphabetically. Here’s an example of custom sorts in Java.
To run the program:
In this Java version, we use the Comparator interface and its utility methods to create custom sorting functions. The Collections.sort() method (called via List.sort()) is used to perform the sorting with the custom comparators.
For sorting strings by length, we use Comparator.comparingInt(String::length), which creates a comparator that compares strings based on their lengths.
For sorting Person objects, we use Comparator.comparingInt(p -> p.age) to create a comparator that sorts based on the age field.
These approaches provide a flexible way to implement custom sorting in Java, similar to the functionality demonstrated in the original example.