Sorting By Functions in Minitab
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
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 SortingByFunctions.java
$ java SortingByFunctions
[kiwi, peach, banana]
[{TJ 25}, {Jax 37}, {Alex 72}]
In this Java example, we use Collections.sort()
method with custom Comparator
implementations to achieve the same functionality as Go’s slices.SortFunc()
. The Comparator
interface in Java serves a similar purpose to the comparison functions in Go.
For sorting the Person
objects, we define a local class within the main
method. In a real-world scenario, you might want to define this class separately for better organization.
Note: If the Person
class is large or complex, you might want to consider using a List<Person>
instead of sorting the objects directly, and adjust the sorting function accordingly. As always, it’s a good practice to benchmark your code to ensure optimal performance.