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 example, we use the Comparator interface to define custom sorting logic. The Comparator.comparingInt method is used to create comparators based on integer values, which is useful for comparing string lengths or ages.
For sorting the list of Person objects, we use a lambda expression to specify the sorting criteria based on the age field. This approach is equivalent to the function we used in the original example.
Note that in Java, we use the sort method on the List interface, which is part of the Collections Framework, rather than a separate sort function. This method modifies the list in place, unlike some implementations in other languages that return a new sorted list.