import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * Another kind of boring use of lambda * Again, all this really does is reduce some a few lines of code * Interestingly, this does require type inference in java * * Created: Oct 7, 2023 * @author gtowell */ public class LamSort { private class Human { String name; int age; public Human(String n, int a) { name = n; age = a; } public String toString() { return "<<" + name + ":" + age + ">>"; } } public static void main(String[] args) { (new LamSort()).doo(); } public void doo() { List humans = Arrays.asList( new Human("Sarah", 10), new Human("Jacky", 52), new Human("Zelda", 33) ); // without lambda implement the Comparable interface Collections.sort(humans, new Comparator() { @Override public int compare(Human h1, Human h2) { return h1.name.compareTo(h2.name); } }); System.out.println(humans); // with lambda, again, implementing the comparable interface // This looks like you are passing a function to the sort, which would imply that // lambda functions are not third class in Java. // But NO. Really passing an object. // Only works because the interface has ONE method. Collections.sort(humans, (a, b) -> a.age - b.age); System.out.println(humans); } }