Sorting By Functions in Java

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.
        // Comparator.comparingInt is helpful for this.
        Comparator<String> lenCmp = Comparator.comparingInt(String::length);

        // Now we can call Collections.sort with this custom
        // comparator 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 Comparator.
        //
        // Note: if the Person class is large,
        // you may want to consider using a list of references
        // to Person objects 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:

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

In this Java version, we use the Comparator interface and its utility methods to create custom sorting functions. The Collections.sort() method (called via List.sort()) is used to perform the sorting with the custom comparators.

For sorting strings by length, we use Comparator.comparingInt(String::length), which creates a comparator that compares strings based on their lengths.

For sorting Person objects, we use Comparator.comparingInt(p -> p.age) to create a comparator that sorts based on the age field.

These approaches provide a flexible way to implement custom sorting in Java, similar to the functionality demonstrated in the original example.