Sorting By Functions in Karel
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 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.
static 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.
//
// Note: if the Person class is large,
// you may want the list to contain Person references instead
// and adjust the sorting function accordingly. If in
// doubt, benchmark!
Collections.sort(people, (a, b) -> Integer.compare(a.age, b.age));
System.out.println(people);
}
}
When you run this program, you’ll see:
[kiwi, peach, banana]
[{TJ 25}, {Jax 37}, {Alex 72}]
In this Java example, we use the Collections.sort
method along with custom Comparator
implementations to achieve custom sorting. The Comparator
interface in Java serves a similar purpose to the comparison functions in the original example.
For sorting the list of Person
objects, we use a lambda expression to create a Comparator
that compares the age
fields. This allows us to sort complex objects based on specific attributes.
Remember that unlike Go’s slices.SortFunc
, which works on slices, Java’s Collections.sort
works on List
implementations. If you need to sort arrays, you can use Arrays.sort
with similar Comparator
arguments.