Modern Java 8+ Features ยท Lambdas and Functional Interfaces

Lambda Expressions

Pass behaviour around as a value. Replace a bulky anonymous class with a one-line lambda, and watch it run each time it is used.

LambdaDemo.java

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class LambdaDemo {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>(List.of("Cara", "Al", "Ben"));

        // Before Java 8: an anonymous class just to say "compare by length"
        Comparator<String> byLengthOld = new Comparator<String>() {
            public int compare(String a, String b) {
                return a.length() - b.length();
            }
        };

        // Java 8: the same thing as a lambda
        Comparator<String> byLength = (a, b) -> a.length() - b.length();
        names.sort(byLength);

        Runnable hello = () -> System.out.println("Sorted: " + names);
        hello.run();
    }
}

Step by step

  1. A list of names to sort by length.
  2. The old way: an anonymous class, five lines just to say "compare by length".
  3. LambdaDemo$1() has finished, so its variables are gone.
  4. The value it returned, {}, is stored in byLengthOld.
  5. The same comparator as a lambda: (a, b) are the parameters, after the arrow is the result.
  6. sort calls the lambda each time it needs to compare two names.
  7. Inside the lambda: comparing two names by length.
  8. b changes from "Al" to "Cara". In the ArrayList that names points to, index 0 changes from "Cara" to "Al" and index 1 changes from "Al" to "Cara".
  9. b changes from "Cara" to "Al".
  10. lambda$main$0() has finished, so its variables are gone. In the ArrayList that names points to, index 1 changes from "Cara" to "Ben" and index 2 changes from "Ben" to "Cara".
  11. A Runnable lambda takes nothing and returns nothing.
  12. Java calls lambda$main$1(), with names = ["Al", "Ben", "Cara"]. It gets its own variables on the stack.
  13. lambda$main$1() has finished, so its variables are gone. It prints Sorted: [Al, Ben, Cara].
  14. Sorted: [Al, Ben, Cara]. Lambdas made both the comparator and the Runnable one line each.