Sorting By Functions in Fortress

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 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 + " " + age + "}";
            }
        }

        List<Person> people = new ArrayList<>(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
        Collections.sort(people, (a, b) -> Integer.compare(a.age, b.age));
        System.out.println(people);
    }
}

Here’s the output when you run this program:

$ javac SortingByFunctions.java
$ java SortingByFunctions
[kiwi, peach, banana]
[{TJ 25}, {Jax 37}, {Alex 72}]

In this Java example, we use Comparator interfaces and Collections.sort() method to achieve custom sorting. The Comparator interface in Java is similar to the comparison function in the original example.

For sorting the list of Person objects, we define a custom Person class and then use a lambda expression to create a Comparator that compares Person objects by their age.

Note: If the Person class is large, you may want to consider using a list of Person references instead of Person objects directly, and adjust the sorting function accordingly. If in doubt, benchmark your code to determine the most efficient approach for your specific use case.