Sorting By Functions in Miranda

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.

import java.util.*;

public class CustomSorting {
    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>(Arrays.asList("peach", "banana", "kiwi"));

        // We implement a comparison function for string lengths using a Comparator.
        Comparator<String> lenCmp = (a, b) -> Integer.compare(a.length(), b.length());

        // Now we can call Collections.sort with this custom Comparator to sort fruits by name length.
        Collections.sort(fruits, lenCmp);
        System.out.println(fruits);

        // We can use the same technique to sort a list of values that aren't built-in types.
        class Person {
            String name;
            int age;

            Person(String name, int age) {
                this.name = name;
                this.age = age;
            }

            @Override
            public String toString() {
                return "{name='" + name + "', age=" + age + "}";
            }
        }

        List<Person> people = Arrays.asList(
            new Person("Jax", 37),
            new Person("TJ", 25),
            new Person("Alex", 72)
        );

        // Sort people by age using Collections.sort with a custom Comparator.
        //
        // Note: if the Person class is large, you may want the list to contain
        // references to Person objects instead. If in doubt, benchmark!
        Collections.sort(people, (a, b) -> Integer.compare(a.age, b.age));
        System.out.println(people);
    }
}

To run the program, compile and execute it using the Java compiler and runtime:

$ javac CustomSorting.java
$ java CustomSorting
[kiwi, peach, banana]
[{name='TJ', age=25}, {name='Jax', age=37}, {name='Alex', age=72}]

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.