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, compile and execute it:
In this Java example, we use the Comparator interface and lambda expressions to create custom sorting functions. The List.sort() method is used instead of a separate sorting function, as Java’s collections have built-in sorting capabilities.
The Person class is defined as an inner class for simplicity, but in a real application, it would typically be a separate class file.
Java 8 and later versions provide convenient methods like Comparator.comparingInt() for creating comparators based on int fields, which we use for sorting the list of Person objects by age.