Sorting By Functions in Logo

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.Arrays;
import java.util.Comparator;
import java.util.List;

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

        // We implement a comparison function for string lengths.
        // Java 8+ lambda expressions are helpful for this.
        Comparator<String> lenCmp = (a, b) -> Integer.compare(a.length(), b.length());

        // Now we can call sort with this custom comparison function to sort fruits by name length.
        fruits.sort(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 a custom Comparator.
        // Note: if the Person class is large, you may want to use a List<Person> instead
        // and adjust the sorting function accordingly. If in doubt, benchmark!
        people.sort(Comparator.comparingInt(p -> p.age));
        System.out.println(people);
    }
}

To run the program, compile and execute it:

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

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.