Sorting By Functions in Squirrel

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 SortingByFunctions {
    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>(Arrays.asList("peach", "banana", "kiwi"));

        // We implement a comparison function for string lengths.
        // Comparator.comparingInt is helpful for this.
        Comparator<String> lenCmp = Comparator.comparingInt(String::length);

        // Now we can call Collections.sort with this custom
        // comparison function 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 + " " + 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.
        Collections.sort(people, Comparator.comparingInt(p -> p.age));
        System.out.println(people);
    }
}

This program will output:

[kiwi, peach, banana]
[{TJ 25}, {Jax 37}, {Alex 72}]

In this Java example, we use Comparator and Collections.sort() to achieve custom sorting. The Comparator.comparingInt() method is used to create comparison functions based on integer values, which is similar to the cmp.Compare function in the original example.

For sorting the list of Person objects, we use a lambda expression to specify the sorting criteria. This approach is equivalent to the anonymous function used in the original example.

Note that in Java, we typically use List interface instead of raw arrays for better flexibility and more built-in functionalities. The Collections.sort() method is used to sort lists, which is analogous to slices.SortFunc() in the original example.

Remember, if the Person class becomes large, you might want to consider using a list of Person references instead of Person objects directly, and adjust the sorting function accordingly. As always, it’s a good practice to benchmark your code to ensure optimal performance.