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 using the Java compiler and runtime:
In this Java example, we use the Collections.sort() method along with custom Comparator implementations to achieve custom sorting. The Comparator interface in Java serves a similar purpose to the comparison functions in the original example.
For sorting built-in types like strings, we create a Comparator that compares the lengths of the strings. For sorting custom types like Person, we create a Comparator that compares the age field.
Java’s Collections.sort() method is used instead of slices.SortFunc(), as Java doesn’t have a direct equivalent to Go’s slice sorting. However, the concept of providing a custom comparison function remains the same.
The Person class is defined as an inner class in this example for simplicity, but in a real-world scenario, it would typically be defined as a separate class.