You need to sort users by age. Writing a separate Comparator class is verbose. Lambda expressions let you write the comparison inline: (a, b) -> a.age - b.age. Anonymous functions in one line.

Basic lambda

Replace anonymous class with lambda.

calcB
Basic.java
Replay: real traced execution (multi-file project)
import java.util.*;

public class Basic {
    public static void main(String[] args) {
        System.out.println("No parameters:\n");

        Runnable task = () -> System.out.println("  Hello from lambda!");
        task.run();

        Runnable oldWay = new Runnable() {
            @Override
            public void run() {
                System.out.println("  Hello from anonymous class");
            }
        };
        oldWay.run();


        System.out.println("\nSingle parameter:");

        interface Printer {
            void print(String message);
        }

        Printer p1 = message -> System.out.println("  " + message);
        p1.print("No parentheses");

        Printer p2 = (message) -> System.out.println("  " + message);
        p2.print("With parentheses");

        System.out.println("\nMultiple parameters:");

        interface Calculator {
            int calculate(int a, int b);
        }

        Calculator add = (a, b) -> a + b;
        Calculator subtract = (a, b) -> a - b;
        Calculator multiply = (a, b) -> a * b;

        int calcB = 3;
        System.out.println("  5 + " + calcB + " = " + add.calculate(5, calcB));
        System.out.println("  5 - " + calcB + " = " + subtract.calculate(5, calcB));
        System.out.println("  5 * " + calcB + " = " + multiply.calculate(5, calcB));

        System.out.println("\nBlock body:");

        Calculator divide = (a, b) -> {
            if (b == 0) {
                System.out.println("  Error: Division by zero");
                return 0;
            }
            return a / b;
        };

        System.out.println("  10 / " + calcB + " = " + divide.calculate(10, calcB));

        System.out.println("\nExplicit types:");

        Calculator power = (int base, int exp) -> {
            int result = 1;
            for (int i = 0; i < exp; i++) {
                result *= base;
            }
            return result;
        };

        System.out.println("  2^3 = " + power.calculate(2, 3));
        System.out.println("  5^2 = " + power.calculate(5, 2));

        System.out.println("\nComparator:");

        List<String> names = new ArrayList<>(Arrays.asList("Charlie", "Alice", "Bob"));
        System.out.println("  Before: " + names);

        names.sort((a, b) -> a.compareTo(b));
        System.out.println("  Sorted: " + names);

        names.sort((a, b) -> b.compareTo(a));
        System.out.println("  Reverse: " + names);
    }
}
import java.util.*;

public class Basic {
    public static void main(String[] args) {
        System.out.println("No parameters:\n");

        Runnable task = () -> System.out.println("  Hello from lambda!");
        task.run();

        Runnable oldWay = new Runnable() {
            @Override
            public void run() {
                System.out.println("  Hello from anonymous class");
            }
        };
        oldWay.run();


        System.out.println("\nSingle parameter:");

        interface Printer {
            void print(String message);
        }

        Printer p1 = message -> System.out.println("  " + message);
        p1.print("No parentheses");

        Printer p2 = (message) -> System.out.println("  " + message);
        p2.print("With parentheses");

        System.out.println("\nMultiple parameters:");

        interface Calculator {
            int calculate(int a, int b);
        }

        Calculator add = (a, b) -> a + b;
        Calculator subtract = (a, b) -> a - b;
        Calculator multiply = (a, b) -> a * b;

        int calcB = 0;
        System.out.println("  5 + " + calcB + " = " + add.calculate(5, calcB));
        System.out.println("  5 - " + calcB + " = " + subtract.calculate(5, calcB));
        System.out.println("  5 * " + calcB + " = " + multiply.calculate(5, calcB));

        System.out.println("\nBlock body:");

        Calculator divide = (a, b) -> {
            if (b == 0) {
                System.out.println("  Error: Division by zero");
                return 0;
            }
            return a / b;
        };

        System.out.println("  10 / " + calcB + " = " + divide.calculate(10, calcB));

        System.out.println("\nExplicit types:");

        Calculator power = (int base, int exp) -> {
            int result = 1;
            for (int i = 0; i < exp; i++) {
                result *= base;
            }
            return result;
        };

        System.out.println("  2^3 = " + power.calculate(2, 3));
        System.out.println("  5^2 = " + power.calculate(5, 2));

        System.out.println("\nComparator:");

        List<String> names = new ArrayList<>(Arrays.asList("Charlie", "Alice", "Bob"));
        System.out.println("  Before: " + names);

        names.sort((a, b) -> a.compareTo(b));
        System.out.println("  Sorted: " + names);

        names.sort((a, b) -> b.compareTo(a));
        System.out.println("  Reverse: " + names);
    }
}
import java.util.*;

public class Basic {
    public static void main(String[] args) {
        System.out.println("No parameters:\n");

        Runnable task = () -> System.out.println("  Hello from lambda!");
        task.run();

        Runnable oldWay = new Runnable() {
            @Override
            public void run() {
                System.out.println("  Hello from anonymous class");
            }
        };
        oldWay.run();


        System.out.println("\nSingle parameter:");

        interface Printer {
            void print(String message);
        }

        Printer p1 = message -> System.out.println("  " + message);
        p1.print("No parentheses");

        Printer p2 = (message) -> System.out.println("  " + message);
        p2.print("With parentheses");

        System.out.println("\nMultiple parameters:");

        interface Calculator {
            int calculate(int a, int b);
        }

        Calculator add = (a, b) -> a + b;
        Calculator subtract = (a, b) -> a - b;
        Calculator multiply = (a, b) -> a * b;

        int calcB = 4;
        System.out.println("  5 + " + calcB + " = " + add.calculate(5, calcB));
        System.out.println("  5 - " + calcB + " = " + subtract.calculate(5, calcB));
        System.out.println("  5 * " + calcB + " = " + multiply.calculate(5, calcB));

        System.out.println("\nBlock body:");

        Calculator divide = (a, b) -> {
            if (b == 0) {
                System.out.println("  Error: Division by zero");
                return 0;
            }
            return a / b;
        };

        System.out.println("  10 / " + calcB + " = " + divide.calculate(10, calcB));

        System.out.println("\nExplicit types:");

        Calculator power = (int base, int exp) -> {
            int result = 1;
            for (int i = 0; i < exp; i++) {
                result *= base;
            }
            return result;
        };

        System.out.println("  2^3 = " + power.calculate(2, 3));
        System.out.println("  5^2 = " + power.calculate(5, 2));

        System.out.println("\nComparator:");

        List<String> names = new ArrayList<>(Arrays.asList("Charlie", "Alice", "Bob"));
        System.out.println("  Before: " + names);

        names.sort((a, b) -> a.compareTo(b));
        System.out.println("  Sorted: " + names);

        names.sort((a, b) -> b.compareTo(a));
        System.out.println("  Reverse: " + names);
    }
}
  1. task ← ⟨Basic lambda A⟩, oldWay ← ⟨Basic$1 B⟩

    3public class Basic {4    public static void main(String[] args) {5        System.out.println("No parameters:\n");6        7        Runnable task→ ⟨Basic lambda A⟩ = () -> System.out.println("  Hello from lambda!");8        task.run();9        10        Runnable oldWay→ ⟨Basic$1 B⟩ = new Runnable() {11            @Override12            public void run() {13                System.out.println("  Hello from anonymous class");14            }15        };16        oldWay.run();
    outputNo parameters:
  2. @Override public void run()

    10Runnable oldWay = new Runnable() {11    @Override12    public void run() {13        System.out.println("  Hello from anonymous class");14    }
    output  Hello from anonymous class
  3. p1 ← ⟨Basic lambda C⟩, p2 ← ⟨Basic lambda D⟩, add ← ⟨Basic lambda E⟩

    15};16oldWay.run();171819System.out.println("\nSingle parameter:");2021interface Printer {22    void print(String message);23}2425Printer p1→ ⟨Basic lambda C⟩ = message -> System.out.println("  " + message);26p1.print("No parentheses");2728Printer p2→ ⟨Basic lambda D⟩ = (message) -> System.out.println("  " + message);29p2.print("With parentheses");3031System.out.println("\nMultiple parameters:");3233interface Calculator {34    int calculate(int a, int b);35}3637Calculator add→ ⟨Basic lambda E⟩ = (a, b) -> a + b;38Calculator subtract→ ⟨Basic lambda F⟩ = (a, b) -> a - b;39Calculator multiply→ ⟨Basic lambda G⟩ = (a, b) -> a * b;4041int calcB→ 3 = 3; //@calcB=3, 0, 442System.out.println("  5 + " + calcB3 + " = " + add.calculate(5, calcB));43System.out.println("  5 - " + calcB3 + " = " + subtract.calculate(5, calcB));44System.out.println("  5 * " + calcB3 + " = " + multiply.calculate(5, calcB));4546System.out.println("\nBlock body:");4748Calculator divide→ ⟨Basic lambda H⟩ = (a, b) -> {49    if (b == 0) {50        System.out.println("  Error: Division by zero");51        return 0;52    }53    return a / b;54};5556System.out.println("  10 / " + calcB3 + " = " + divide.calculate(10, calcB));
    output
    Single parameter:
    
    Multiple parameters:
      5 + 3 = 8
      5 - 3 = 2
      5 * 3 = 15
    
    Block body:
  4. power ← ⟨Basic lambda I⟩

    56System.out.println("  10 / " + calcB3 + " = " + divide.calculate(10, calcB));5758System.out.println("\nExplicit types:");5960Calculator power→ ⟨Basic lambda I⟩ = (int base, int exp) -> {61    int result = 1;62    for (int i = 0; i < exp; i++) {63        result *= base;64    }65    return result;66};6768System.out.println("  2^3 = " + power.calculate(2, 3));69System.out.println("  5^2 = " + power.calculate(5, 2));
    output  10 / 3 = 3
    
    Explicit types:
  5. return result;

    64    }65    return result;66};
  6. System.out.println(" 2^3 = " + power.calculate(2, 3));

    68System.out.println("  2^3 = " + power.calculate(2, 3));69System.out.println("  5^2 = " + power.calculate(5, 2));
    output  2^3 = 8
  7. return result;

    64    }65    return result;66};
  8. names ← [Charlie, Alice, Bob]

    68    System.out.println("  2^3 = " + power.calculate(2, 3));69    System.out.println("  5^2 = " + power.calculate(5, 2));70    71    System.out.println("\nComparator:");72    73    List<String> names→ [Charlie, Alice, Bob] = new ArrayList<>(Arrays.asList("Charlie", "Alice", "Bob"));74    System.out.println("  Before: " + names[Charlie, Alice, Bob]);75    76    names.sort((a, b) -> a.compareTo(b));77    System.out.println("  Sorted: " + names[Alice, Bob, Charlie]);78    79    names.sort((a, b) -> b.compareTo(a));80    System.out.println("  Reverse: " + names[Charlie, Bob, Alice]);81}
    output  5^2 = 25
    
    Comparator:
      Before: [Charlie, Alice, Bob]
      Sorted: [Alice, Bob, Charlie]
      Reverse: [Charlie, Bob, Alice]
  1. task ← ⟨Basic lambda A⟩, oldWay ← ⟨Basic$1 B⟩

    3public class Basic {4    public static void main(String[] args) {5        System.out.println("No parameters:\n");6        7        Runnable task→ ⟨Basic lambda A⟩ = () -> System.out.println("  Hello from lambda!");8        task.run();9        10        Runnable oldWay→ ⟨Basic$1 B⟩ = new Runnable() {11            @Override12            public void run() {13                System.out.println("  Hello from anonymous class");14            }15        };16        oldWay.run();
    outputNo parameters:
  2. @Override public void run()

    10Runnable oldWay = new Runnable() {11    @Override12    public void run() {13        System.out.println("  Hello from anonymous class");14    }
    output  Hello from anonymous class
  3. p1 ← ⟨Basic lambda C⟩, p2 ← ⟨Basic lambda D⟩, add ← ⟨Basic lambda E⟩

    15};16oldWay.run();171819System.out.println("\nSingle parameter:");2021interface Printer {22    void print(String message);23}2425Printer p1→ ⟨Basic lambda C⟩ = message -> System.out.println("  " + message);26p1.print("No parentheses");2728Printer p2→ ⟨Basic lambda D⟩ = (message) -> System.out.println("  " + message);29p2.print("With parentheses");3031System.out.println("\nMultiple parameters:");3233interface Calculator {34    int calculate(int a, int b);35}3637Calculator add→ ⟨Basic lambda E⟩ = (a, b) -> a + b;38Calculator subtract→ ⟨Basic lambda F⟩ = (a, b) -> a - b;39Calculator multiply→ ⟨Basic lambda G⟩ = (a, b) -> a * b;4041int calcB→ 0 = 0;42System.out.println("  5 + " + calcB0 + " = " + add.calculate(5, calcB));43System.out.println("  5 - " + calcB0 + " = " + subtract.calculate(5, calcB));44System.out.println("  5 * " + calcB0 + " = " + multiply.calculate(5, calcB));4546System.out.println("\nBlock body:");4748Calculator divide→ ⟨Basic lambda H⟩ = (a, b) -> {49    if (b == 0) {50        System.out.println("  Error: Division by zero");51        return 0;52    }53    return a / b;54};5556System.out.println("  10 / " + calcB0 + " = " + divide.calculate(10, calcB));
    output
    Single parameter:
    
    Multiple parameters:
      5 + 0 = 5
      5 - 0 = 5
      5 * 0 = 0
    
    Block body:
  4. if (b == 0)

    48Calculator divide = (a, b) -> {49    if (b == 0) {50        System.out.println("  Error: Division by zero");51        return 0;52    }
    output  Error: Division by zero
  5. power ← ⟨Basic lambda I⟩

    56System.out.println("  10 / " + calcB0 + " = " + divide.calculate(10, calcB));5758System.out.println("\nExplicit types:");5960Calculator power→ ⟨Basic lambda I⟩ = (int base, int exp) -> {61    int result = 1;62    for (int i = 0; i < exp; i++) {63        result *= base;64    }65    return result;66};6768System.out.println("  2^3 = " + power.calculate(2, 3));69System.out.println("  5^2 = " + power.calculate(5, 2));
    output  10 / 0 = 0
    
    Explicit types:
  6. return result;

    64    }65    return result;66};
  7. System.out.println(" 2^3 = " + power.calculate(2, 3));

    68System.out.println("  2^3 = " + power.calculate(2, 3));69System.out.println("  5^2 = " + power.calculate(5, 2));
    output  2^3 = 8
  8. return result;

    64    }65    return result;66};
  9. names ← [Charlie, Alice, Bob]

    68    System.out.println("  2^3 = " + power.calculate(2, 3));69    System.out.println("  5^2 = " + power.calculate(5, 2));70    71    System.out.println("\nComparator:");72    73    List<String> names→ [Charlie, Alice, Bob] = new ArrayList<>(Arrays.asList("Charlie", "Alice", "Bob"));74    System.out.println("  Before: " + names[Charlie, Alice, Bob]);75    76    names.sort((a, b) -> a.compareTo(b));77    System.out.println("  Sorted: " + names[Alice, Bob, Charlie]);78    79    names.sort((a, b) -> b.compareTo(a));80    System.out.println("  Reverse: " + names[Charlie, Bob, Alice]);81}
    output  5^2 = 25
    
    Comparator:
      Before: [Charlie, Alice, Bob]
      Sorted: [Alice, Bob, Charlie]
      Reverse: [Charlie, Bob, Alice]
  1. task ← ⟨Basic lambda A⟩, oldWay ← ⟨Basic$1 B⟩

    3public class Basic {4    public static void main(String[] args) {5        System.out.println("No parameters:\n");6        7        Runnable task→ ⟨Basic lambda A⟩ = () -> System.out.println("  Hello from lambda!");8        task.run();9        10        Runnable oldWay→ ⟨Basic$1 B⟩ = new Runnable() {11            @Override12            public void run() {13                System.out.println("  Hello from anonymous class");14            }15        };16        oldWay.run();
    outputNo parameters:
  2. @Override public void run()

    10Runnable oldWay = new Runnable() {11    @Override12    public void run() {13        System.out.println("  Hello from anonymous class");14    }
    output  Hello from anonymous class
  3. p1 ← ⟨Basic lambda C⟩, p2 ← ⟨Basic lambda D⟩, add ← ⟨Basic lambda E⟩

    15};16oldWay.run();171819System.out.println("\nSingle parameter:");2021interface Printer {22    void print(String message);23}2425Printer p1→ ⟨Basic lambda C⟩ = message -> System.out.println("  " + message);26p1.print("No parentheses");2728Printer p2→ ⟨Basic lambda D⟩ = (message) -> System.out.println("  " + message);29p2.print("With parentheses");3031System.out.println("\nMultiple parameters:");3233interface Calculator {34    int calculate(int a, int b);35}3637Calculator add→ ⟨Basic lambda E⟩ = (a, b) -> a + b;38Calculator subtract→ ⟨Basic lambda F⟩ = (a, b) -> a - b;39Calculator multiply→ ⟨Basic lambda G⟩ = (a, b) -> a * b;4041int calcB→ 4 = 4;42System.out.println("  5 + " + calcB4 + " = " + add.calculate(5, calcB));43System.out.println("  5 - " + calcB4 + " = " + subtract.calculate(5, calcB));44System.out.println("  5 * " + calcB4 + " = " + multiply.calculate(5, calcB));4546System.out.println("\nBlock body:");4748Calculator divide→ ⟨Basic lambda H⟩ = (a, b) -> {49    if (b == 0) {50        System.out.println("  Error: Division by zero");51        return 0;52    }53    return a / b;54};5556System.out.println("  10 / " + calcB4 + " = " + divide.calculate(10, calcB));
    output
    Single parameter:
    
    Multiple parameters:
      5 + 4 = 9
      5 - 4 = 1
      5 * 4 = 20
    
    Block body:
  4. power ← ⟨Basic lambda I⟩

    56System.out.println("  10 / " + calcB4 + " = " + divide.calculate(10, calcB));5758System.out.println("\nExplicit types:");5960Calculator power→ ⟨Basic lambda I⟩ = (int base, int exp) -> {61    int result = 1;62    for (int i = 0; i < exp; i++) {63        result *= base;64    }65    return result;66};6768System.out.println("  2^3 = " + power.calculate(2, 3));69System.out.println("  5^2 = " + power.calculate(5, 2));
    output  10 / 4 = 2
    
    Explicit types:
  5. return result;

    64    }65    return result;66};
  6. System.out.println(" 2^3 = " + power.calculate(2, 3));

    68System.out.println("  2^3 = " + power.calculate(2, 3));69System.out.println("  5^2 = " + power.calculate(5, 2));
    output  2^3 = 8
  7. return result;

    64    }65    return result;66};
  8. names ← [Charlie, Alice, Bob]

    68    System.out.println("  2^3 = " + power.calculate(2, 3));69    System.out.println("  5^2 = " + power.calculate(5, 2));70    71    System.out.println("\nComparator:");72    73    List<String> names→ [Charlie, Alice, Bob] = new ArrayList<>(Arrays.asList("Charlie", "Alice", "Bob"));74    System.out.println("  Before: " + names[Charlie, Alice, Bob]);75    76    names.sort((a, b) -> a.compareTo(b));77    System.out.println("  Sorted: " + names[Alice, Bob, Charlie]);78    79    names.sort((a, b) -> b.compareTo(a));80    System.out.println("  Reverse: " + names[Charlie, Bob, Alice]);81}
    output  5^2 = 25
    
    Comparator:
      Before: [Charlie, Alice, Bob]
      Sorted: [Alice, Bob, Charlie]
      Reverse: [Charlie, Bob, Alice]

(params) -> expression - concise syntax for single-method interfaces.

lambda Anonymous function: `(x, y) -> x + y`. Implements functional interface.

Lambda parameters

Different ways to specify parameters.

repeatCount
Parameters.java
Replay: real traced execution (multi-file project)
import java.util.*;
import java.util.function.*;

public class Parameters {
    public static void main(String[] args) {
        System.out.println("Single parameter:\n");

        UnaryOperator<Integer> square = x -> x * x;
        UnaryOperator<Integer> doubler = x -> x * 2;
        UnaryOperator<String> upper = s -> s.toUpperCase();

        System.out.println("  square(5) = " + square.apply(5));
        System.out.println("  doubler(7) = " + doubler.apply(7));
        System.out.println("  upper('hello') = " + upper.apply("hello"));


        System.out.println("\nTwo parameters:");

        BinaryOperator<Integer> max = (a, b) -> a > b ? a : b;
        BinaryOperator<Integer> min = (a, b) -> a < b ? a : b;
        BinaryOperator<String> concat = (s1, s2) -> s1 + s2;

        System.out.println("  max(10, 20) = " + max.apply(10, 20));
        System.out.println("  min(10, 20) = " + min.apply(10, 20));
        System.out.println("  concat('Hello', ' World') = " + concat.apply("Hello", " World"));

        System.out.println("\nDifferent input/output types:");

        BiFunction<String, Integer, String> repeat = (str, n) -> {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < n; i++) {
                sb.append(str);
            }
            return sb.toString();
        };

        BiFunction<Integer, Integer, Double> divide = (a, b) -> (double) a / b;

        int repeatCount = 3;
        System.out.println("  repeat('ab', " + repeatCount + ") = " +
                           repeat.apply("ab", repeatCount));
        System.out.println("  divide(10, 4) = " + divide.apply(10, 4));

        System.out.println("\nBlock with parameters:");

        BiFunction<Integer, Integer, String> compare = (a, b) -> {
            if (a > b) {
                return a + " is greater";
            } else if (a < b) {
                return b + " is greater";
            } else {
                return "Equal";
            }
        };

        System.out.println("  compare(10, 5): " + compare.apply(10, 5));
        System.out.println("  compare(3, 8): " + compare.apply(3, 8));
        System.out.println("  compare(7, 7): " + compare.apply(7, 7));

        System.out.println("\nList operations:");

        List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));

        System.out.print("  Numbers: ");
        numbers.forEach(n -> System.out.print(n + " "));
        System.out.println();

        numbers.removeIf(n -> n % 2 == 0);
        System.out.println("  After removing evens: " + numbers);

        System.out.println("\nCustom interface:");

        interface Validator {
            boolean validate(String input);
        }

        Validator notEmpty = s -> s != null && !s.isEmpty();
        Validator isEmail = s -> s.contains("@");
        Validator minLength = s -> s.length() >= 5;

        String test1 = "user@example.com";
        String test2 = "ab";

        System.out.println("  '" + test1 + "' not empty: " + notEmpty.validate(test1));
        System.out.println("  '" + test1 + "' is email: " + isEmail.validate(test1));
        System.out.println("  '" + test2 + "' min length: " + minLength.validate(test2));
    }
}
import java.util.*;
import java.util.function.*;

public class Parameters {
    public static void main(String[] args) {
        System.out.println("Single parameter:\n");

        UnaryOperator<Integer> square = x -> x * x;
        UnaryOperator<Integer> doubler = x -> x * 2;
        UnaryOperator<String> upper = s -> s.toUpperCase();

        System.out.println("  square(5) = " + square.apply(5));
        System.out.println("  doubler(7) = " + doubler.apply(7));
        System.out.println("  upper('hello') = " + upper.apply("hello"));


        System.out.println("\nTwo parameters:");

        BinaryOperator<Integer> max = (a, b) -> a > b ? a : b;
        BinaryOperator<Integer> min = (a, b) -> a < b ? a : b;
        BinaryOperator<String> concat = (s1, s2) -> s1 + s2;

        System.out.println("  max(10, 20) = " + max.apply(10, 20));
        System.out.println("  min(10, 20) = " + min.apply(10, 20));
        System.out.println("  concat('Hello', ' World') = " + concat.apply("Hello", " World"));

        System.out.println("\nDifferent input/output types:");

        BiFunction<String, Integer, String> repeat = (str, n) -> {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < n; i++) {
                sb.append(str);
            }
            return sb.toString();
        };

        BiFunction<Integer, Integer, Double> divide = (a, b) -> (double) a / b;

        int repeatCount = 1;
        System.out.println("  repeat('ab', " + repeatCount + ") = " +
                           repeat.apply("ab", repeatCount));
        System.out.println("  divide(10, 4) = " + divide.apply(10, 4));

        System.out.println("\nBlock with parameters:");

        BiFunction<Integer, Integer, String> compare = (a, b) -> {
            if (a > b) {
                return a + " is greater";
            } else if (a < b) {
                return b + " is greater";
            } else {
                return "Equal";
            }
        };

        System.out.println("  compare(10, 5): " + compare.apply(10, 5));
        System.out.println("  compare(3, 8): " + compare.apply(3, 8));
        System.out.println("  compare(7, 7): " + compare.apply(7, 7));

        System.out.println("\nList operations:");

        List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));

        System.out.print("  Numbers: ");
        numbers.forEach(n -> System.out.print(n + " "));
        System.out.println();

        numbers.removeIf(n -> n % 2 == 0);
        System.out.println("  After removing evens: " + numbers);

        System.out.println("\nCustom interface:");

        interface Validator {
            boolean validate(String input);
        }

        Validator notEmpty = s -> s != null && !s.isEmpty();
        Validator isEmail = s -> s.contains("@");
        Validator minLength = s -> s.length() >= 5;

        String test1 = "user@example.com";
        String test2 = "ab";

        System.out.println("  '" + test1 + "' not empty: " + notEmpty.validate(test1));
        System.out.println("  '" + test1 + "' is email: " + isEmail.validate(test1));
        System.out.println("  '" + test2 + "' min length: " + minLength.validate(test2));
    }
}
import java.util.*;
import java.util.function.*;

public class Parameters {
    public static void main(String[] args) {
        System.out.println("Single parameter:\n");

        UnaryOperator<Integer> square = x -> x * x;
        UnaryOperator<Integer> doubler = x -> x * 2;
        UnaryOperator<String> upper = s -> s.toUpperCase();

        System.out.println("  square(5) = " + square.apply(5));
        System.out.println("  doubler(7) = " + doubler.apply(7));
        System.out.println("  upper('hello') = " + upper.apply("hello"));


        System.out.println("\nTwo parameters:");

        BinaryOperator<Integer> max = (a, b) -> a > b ? a : b;
        BinaryOperator<Integer> min = (a, b) -> a < b ? a : b;
        BinaryOperator<String> concat = (s1, s2) -> s1 + s2;

        System.out.println("  max(10, 20) = " + max.apply(10, 20));
        System.out.println("  min(10, 20) = " + min.apply(10, 20));
        System.out.println("  concat('Hello', ' World') = " + concat.apply("Hello", " World"));

        System.out.println("\nDifferent input/output types:");

        BiFunction<String, Integer, String> repeat = (str, n) -> {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < n; i++) {
                sb.append(str);
            }
            return sb.toString();
        };

        BiFunction<Integer, Integer, Double> divide = (a, b) -> (double) a / b;

        int repeatCount = 5;
        System.out.println("  repeat('ab', " + repeatCount + ") = " +
                           repeat.apply("ab", repeatCount));
        System.out.println("  divide(10, 4) = " + divide.apply(10, 4));

        System.out.println("\nBlock with parameters:");

        BiFunction<Integer, Integer, String> compare = (a, b) -> {
            if (a > b) {
                return a + " is greater";
            } else if (a < b) {
                return b + " is greater";
            } else {
                return "Equal";
            }
        };

        System.out.println("  compare(10, 5): " + compare.apply(10, 5));
        System.out.println("  compare(3, 8): " + compare.apply(3, 8));
        System.out.println("  compare(7, 7): " + compare.apply(7, 7));

        System.out.println("\nList operations:");

        List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));

        System.out.print("  Numbers: ");
        numbers.forEach(n -> System.out.print(n + " "));
        System.out.println();

        numbers.removeIf(n -> n % 2 == 0);
        System.out.println("  After removing evens: " + numbers);

        System.out.println("\nCustom interface:");

        interface Validator {
            boolean validate(String input);
        }

        Validator notEmpty = s -> s != null && !s.isEmpty();
        Validator isEmail = s -> s.contains("@");
        Validator minLength = s -> s.length() >= 5;

        String test1 = "user@example.com";
        String test2 = "ab";

        System.out.println("  '" + test1 + "' not empty: " + notEmpty.validate(test1));
        System.out.println("  '" + test1 + "' is email: " + isEmail.validate(test1));
        System.out.println("  '" + test2 + "' min length: " + minLength.validate(test2));
    }
}
  1. square ← ⟨Parameters lambda A⟩, doubler ← ⟨Parameters lambda B⟩

    4public class Parameters {5    public static void main(String[] args) {6        System.out.println("Single parameter:\n");7        8        UnaryOperator<Integer> square→ ⟨Parameters lambda A⟩ = x -> x * x;9        UnaryOperator<Integer> doubler→ ⟨Parameters lambda B⟩ = x -> x * 2;10        UnaryOperator<String> upper→ ⟨Parameters lambda C⟩ = s -> s.toUpperCase();11        12        System.out.println("  square(5) = " + square.apply(5));13        System.out.println("  doubler(7) = " + doubler.apply(7));14        System.out.println("  upper('hello') = " + upper.apply("hello"));15        16        17        System.out.println("\nTwo parameters:");18        19        BinaryOperator<Integer> max→ ⟨Parameters lambda D⟩ = (a, b) -> a > b ? a : b;20        BinaryOperator<Integer> min→ ⟨Parameters lambda E⟩ = (a, b) -> a < b ? a : b;21        BinaryOperator<String> concat→ ⟨Parameters lambda F⟩ = (s1, s2) -> s1 + s2;22        23        System.out.println("  max(10, 20) = " + max.apply(10, 20));24        System.out.println("  min(10, 20) = " + min.apply(10, 20));25        System.out.println("  concat('Hello', ' World') = " + concat.apply("Hello", " World"));26        27        System.out.println("\nDifferent input/output types:");28        29        BiFunction<String, Integer, String> repeat→ ⟨Parameters lambda G⟩ = (str, n) -> {30            StringBuilder sb = new StringBuilder();31            for (int i = 0; i < n; i++) {32                sb.append(str);33            }34            return sb.toString();35        };36        37        BiFunction<Integer, Integer, Double> divide→ ⟨Parameters lambda H⟩ = (a, b) -> (double) a / b;38        39        int repeatCount→ 3 = 3; //@repeatCount=3, 1, 540        System.out.println("  repeat('ab', " + repeatCount3 + ") = " +41                           repeat.apply("ab", repeatCount3));42        System.out.println("  divide(10, 4) = " + divide.apply(10, 4));
    outputSingle parameter:
      square(5) = 25
      doubler(7) = 14
      upper('hello') = HELLO
    
    Two parameters:
      max(10, 20) = 20
      min(10, 20) = 10
      concat('Hello', ' World') = Hello World
    
    Different input/output types:
  2. return sb.toString();

    33    }34    return sb.toString();35};
  3. compare ← ⟨Parameters lambda I⟩

    39int repeatCount = 3; //@repeatCount=3, 1, 540System.out.println("  repeat('ab', " + repeatCount3 + ") = " +41                   repeat.apply("ab", repeatCount3));42System.out.println("  divide(10, 4) = " + divide.apply(10, 4));4344System.out.println("\nBlock with parameters:");4546BiFunction<Integer, Integer, String> compare→ ⟨Parameters lambda I⟩ = (a, b) -> {47    if (a > b) {48        return a + " is greater";49    } else if (a < b) {50        return b + " is greater";51    } else {52        return "Equal";53    }54};5556System.out.println("  compare(10, 5): " + compare.apply(10, 5));57System.out.println("  compare(3, 8): " + compare.apply(3, 8));
    output  repeat('ab', 3) = ababab
      divide(10, 4) = 2.5
    
    Block with parameters:
  4. System.out.println(" compare(10, 5): " + compare.apply(10, 5));

    56System.out.println("  compare(10, 5): " + compare.apply(10, 5));57System.out.println("  compare(3, 8): " + compare.apply(3, 8));58System.out.println("  compare(7, 7): " + compare.apply(7, 7));
    output  compare(10, 5): 10 is greater
  5. System.out.println(" compare(3, 8): " + compare.apply(3, 8));

    56System.out.println("  compare(10, 5): " + compare.apply(10, 5));57System.out.println("  compare(3, 8): " + compare.apply(3, 8));58System.out.println("  compare(7, 7): " + compare.apply(7, 7));
    output  compare(3, 8): 8 is greater
  6. numbers ← [1, 2, 3, 4, 5], notEmpty ← ⟨Parameters lambda J⟩, isEmail ← ⟨Parameters lambda K⟩

    57    System.out.println("  compare(3, 8): " + compare.apply(3, 8));58    System.out.println("  compare(7, 7): " + compare.apply(7, 7));59    60    System.out.println("\nList operations:");61    62    List<Integer> numbers→ [1, 2, 3, 4, 5] = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));63    64    System.out.print("  Numbers: ");65    numbers.forEach(n -> System.out.print(n + " "));66    System.out.println();67    68    numbers.removeIf(n -> n % 2 == 0);69    System.out.println("  After removing evens: " + numbers[1, 3, 5]);70    71    System.out.println("\nCustom interface:");72    73    interface Validator {74        boolean validate(String input);75    }76    77    Validator notEmpty→ ⟨Parameters lambda J⟩ = s -> s != null && !s.isEmpty();78    Validator isEmail→ ⟨Parameters lambda K⟩ = s -> s.contains("@");79    Validator minLength→ ⟨Parameters lambda L⟩ = s -> s.length() >= 5;80    81    String test1→ user@example.com = "user@example.com";82    String test2→ ab = "ab";83    84    System.out.println("  '" + test1user@example.com + "' not empty: " + notEmpty.validate(test1));85    System.out.println("  '" + test1user@example.com + "' is email: " + isEmail.validate(test1));86    System.out.println("  '" + test2ab + "' min length: " + minLength.validate(test2));87}
    output  compare(7, 7): Equal
    
    List operations:
      Numbers:
      After removing evens: [1, 3, 5]
    
    Custom interface:
      'user@example.com' not empty: true
      'user@example.com' is email: true
      'ab' min length: false
  1. square ← ⟨Parameters lambda A⟩, doubler ← ⟨Parameters lambda B⟩

    4public class Parameters {5    public static void main(String[] args) {6        System.out.println("Single parameter:\n");7        8        UnaryOperator<Integer> square→ ⟨Parameters lambda A⟩ = x -> x * x;9        UnaryOperator<Integer> doubler→ ⟨Parameters lambda B⟩ = x -> x * 2;10        UnaryOperator<String> upper→ ⟨Parameters lambda C⟩ = s -> s.toUpperCase();11        12        System.out.println("  square(5) = " + square.apply(5));13        System.out.println("  doubler(7) = " + doubler.apply(7));14        System.out.println("  upper('hello') = " + upper.apply("hello"));15        16        17        System.out.println("\nTwo parameters:");18        19        BinaryOperator<Integer> max→ ⟨Parameters lambda D⟩ = (a, b) -> a > b ? a : b;20        BinaryOperator<Integer> min→ ⟨Parameters lambda E⟩ = (a, b) -> a < b ? a : b;21        BinaryOperator<String> concat→ ⟨Parameters lambda F⟩ = (s1, s2) -> s1 + s2;22        23        System.out.println("  max(10, 20) = " + max.apply(10, 20));24        System.out.println("  min(10, 20) = " + min.apply(10, 20));25        System.out.println("  concat('Hello', ' World') = " + concat.apply("Hello", " World"));26        27        System.out.println("\nDifferent input/output types:");28        29        BiFunction<String, Integer, String> repeat→ ⟨Parameters lambda G⟩ = (str, n) -> {30            StringBuilder sb = new StringBuilder();31            for (int i = 0; i < n; i++) {32                sb.append(str);33            }34            return sb.toString();35        };36        37        BiFunction<Integer, Integer, Double> divide→ ⟨Parameters lambda H⟩ = (a, b) -> (double) a / b;38        39        int repeatCount→ 1 = 1;40        System.out.println("  repeat('ab', " + repeatCount1 + ") = " +41                           repeat.apply("ab", repeatCount1));42        System.out.println("  divide(10, 4) = " + divide.apply(10, 4));
    outputSingle parameter:
      square(5) = 25
      doubler(7) = 14
      upper('hello') = HELLO
    
    Two parameters:
      max(10, 20) = 20
      min(10, 20) = 10
      concat('Hello', ' World') = Hello World
    
    Different input/output types:
  2. return sb.toString();

    33    }34    return sb.toString();35};
  3. compare ← ⟨Parameters lambda I⟩

    39int repeatCount = 1;40System.out.println("  repeat('ab', " + repeatCount1 + ") = " +41                   repeat.apply("ab", repeatCount1));42System.out.println("  divide(10, 4) = " + divide.apply(10, 4));4344System.out.println("\nBlock with parameters:");4546BiFunction<Integer, Integer, String> compare→ ⟨Parameters lambda I⟩ = (a, b) -> {47    if (a > b) {48        return a + " is greater";49    } else if (a < b) {50        return b + " is greater";51    } else {52        return "Equal";53    }54};5556System.out.println("  compare(10, 5): " + compare.apply(10, 5));57System.out.println("  compare(3, 8): " + compare.apply(3, 8));
    output  repeat('ab', 1) = ab
      divide(10, 4) = 2.5
    
    Block with parameters:
  4. System.out.println(" compare(10, 5): " + compare.apply(10, 5));

    56System.out.println("  compare(10, 5): " + compare.apply(10, 5));57System.out.println("  compare(3, 8): " + compare.apply(3, 8));58System.out.println("  compare(7, 7): " + compare.apply(7, 7));
    output  compare(10, 5): 10 is greater
  5. System.out.println(" compare(3, 8): " + compare.apply(3, 8));

    56System.out.println("  compare(10, 5): " + compare.apply(10, 5));57System.out.println("  compare(3, 8): " + compare.apply(3, 8));58System.out.println("  compare(7, 7): " + compare.apply(7, 7));
    output  compare(3, 8): 8 is greater
  6. numbers ← [1, 2, 3, 4, 5], notEmpty ← ⟨Parameters lambda J⟩, isEmail ← ⟨Parameters lambda K⟩

    57    System.out.println("  compare(3, 8): " + compare.apply(3, 8));58    System.out.println("  compare(7, 7): " + compare.apply(7, 7));59    60    System.out.println("\nList operations:");61    62    List<Integer> numbers→ [1, 2, 3, 4, 5] = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));63    64    System.out.print("  Numbers: ");65    numbers.forEach(n -> System.out.print(n + " "));66    System.out.println();67    68    numbers.removeIf(n -> n % 2 == 0);69    System.out.println("  After removing evens: " + numbers[1, 3, 5]);70    71    System.out.println("\nCustom interface:");72    73    interface Validator {74        boolean validate(String input);75    }76    77    Validator notEmpty→ ⟨Parameters lambda J⟩ = s -> s != null && !s.isEmpty();78    Validator isEmail→ ⟨Parameters lambda K⟩ = s -> s.contains("@");79    Validator minLength→ ⟨Parameters lambda L⟩ = s -> s.length() >= 5;80    81    String test1→ user@example.com = "user@example.com";82    String test2→ ab = "ab";83    84    System.out.println("  '" + test1user@example.com + "' not empty: " + notEmpty.validate(test1));85    System.out.println("  '" + test1user@example.com + "' is email: " + isEmail.validate(test1));86    System.out.println("  '" + test2ab + "' min length: " + minLength.validate(test2));87}
    output  compare(7, 7): Equal
    
    List operations:
      Numbers:
      After removing evens: [1, 3, 5]
    
    Custom interface:
      'user@example.com' not empty: true
      'user@example.com' is email: true
      'ab' min length: false
  1. square ← ⟨Parameters lambda A⟩, doubler ← ⟨Parameters lambda B⟩

    4public class Parameters {5    public static void main(String[] args) {6        System.out.println("Single parameter:\n");7        8        UnaryOperator<Integer> square→ ⟨Parameters lambda A⟩ = x -> x * x;9        UnaryOperator<Integer> doubler→ ⟨Parameters lambda B⟩ = x -> x * 2;10        UnaryOperator<String> upper→ ⟨Parameters lambda C⟩ = s -> s.toUpperCase();11        12        System.out.println("  square(5) = " + square.apply(5));13        System.out.println("  doubler(7) = " + doubler.apply(7));14        System.out.println("  upper('hello') = " + upper.apply("hello"));15        16        17        System.out.println("\nTwo parameters:");18        19        BinaryOperator<Integer> max→ ⟨Parameters lambda D⟩ = (a, b) -> a > b ? a : b;20        BinaryOperator<Integer> min→ ⟨Parameters lambda E⟩ = (a, b) -> a < b ? a : b;21        BinaryOperator<String> concat→ ⟨Parameters lambda F⟩ = (s1, s2) -> s1 + s2;22        23        System.out.println("  max(10, 20) = " + max.apply(10, 20));24        System.out.println("  min(10, 20) = " + min.apply(10, 20));25        System.out.println("  concat('Hello', ' World') = " + concat.apply("Hello", " World"));26        27        System.out.println("\nDifferent input/output types:");28        29        BiFunction<String, Integer, String> repeat→ ⟨Parameters lambda G⟩ = (str, n) -> {30            StringBuilder sb = new StringBuilder();31            for (int i = 0; i < n; i++) {32                sb.append(str);33            }34            return sb.toString();35        };36        37        BiFunction<Integer, Integer, Double> divide→ ⟨Parameters lambda H⟩ = (a, b) -> (double) a / b;38        39        int repeatCount→ 5 = 5;40        System.out.println("  repeat('ab', " + repeatCount5 + ") = " +41                           repeat.apply("ab", repeatCount5));42        System.out.println("  divide(10, 4) = " + divide.apply(10, 4));
    outputSingle parameter:
      square(5) = 25
      doubler(7) = 14
      upper('hello') = HELLO
    
    Two parameters:
      max(10, 20) = 20
      min(10, 20) = 10
      concat('Hello', ' World') = Hello World
    
    Different input/output types:
  2. return sb.toString();

    33    }34    return sb.toString();35};
  3. compare ← ⟨Parameters lambda I⟩

    39int repeatCount = 5;40System.out.println("  repeat('ab', " + repeatCount5 + ") = " +41                   repeat.apply("ab", repeatCount5));42System.out.println("  divide(10, 4) = " + divide.apply(10, 4));4344System.out.println("\nBlock with parameters:");4546BiFunction<Integer, Integer, String> compare→ ⟨Parameters lambda I⟩ = (a, b) -> {47    if (a > b) {48        return a + " is greater";49    } else if (a < b) {50        return b + " is greater";51    } else {52        return "Equal";53    }54};5556System.out.println("  compare(10, 5): " + compare.apply(10, 5));57System.out.println("  compare(3, 8): " + compare.apply(3, 8));
    output  repeat('ab', 5) = ababababab
      divide(10, 4) = 2.5
    
    Block with parameters:
  4. System.out.println(" compare(10, 5): " + compare.apply(10, 5));

    56System.out.println("  compare(10, 5): " + compare.apply(10, 5));57System.out.println("  compare(3, 8): " + compare.apply(3, 8));58System.out.println("  compare(7, 7): " + compare.apply(7, 7));
    output  compare(10, 5): 10 is greater
  5. System.out.println(" compare(3, 8): " + compare.apply(3, 8));

    56System.out.println("  compare(10, 5): " + compare.apply(10, 5));57System.out.println("  compare(3, 8): " + compare.apply(3, 8));58System.out.println("  compare(7, 7): " + compare.apply(7, 7));
    output  compare(3, 8): 8 is greater
  6. numbers ← [1, 2, 3, 4, 5], notEmpty ← ⟨Parameters lambda J⟩, isEmail ← ⟨Parameters lambda K⟩

    57    System.out.println("  compare(3, 8): " + compare.apply(3, 8));58    System.out.println("  compare(7, 7): " + compare.apply(7, 7));59    60    System.out.println("\nList operations:");61    62    List<Integer> numbers→ [1, 2, 3, 4, 5] = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));63    64    System.out.print("  Numbers: ");65    numbers.forEach(n -> System.out.print(n + " "));66    System.out.println();67    68    numbers.removeIf(n -> n % 2 == 0);69    System.out.println("  After removing evens: " + numbers[1, 3, 5]);70    71    System.out.println("\nCustom interface:");72    73    interface Validator {74        boolean validate(String input);75    }76    77    Validator notEmpty→ ⟨Parameters lambda J⟩ = s -> s != null && !s.isEmpty();78    Validator isEmail→ ⟨Parameters lambda K⟩ = s -> s.contains("@");79    Validator minLength→ ⟨Parameters lambda L⟩ = s -> s.length() >= 5;80    81    String test1→ user@example.com = "user@example.com";82    String test2→ ab = "ab";83    84    System.out.println("  '" + test1user@example.com + "' not empty: " + notEmpty.validate(test1));85    System.out.println("  '" + test1user@example.com + "' is email: " + isEmail.validate(test1));86    System.out.println("  '" + test2ab + "' min length: " + minLength.validate(test2));87}
    output  compare(7, 7): Equal
    
    List operations:
      Numbers:
      After removing evens: [1, 3, 5]
    
    Custom interface:
      'user@example.com' not empty: true
      'user@example.com' is email: true
      'ab' min length: false

x -> x*2 (one param, no parens), (x, y) -> x+y (multiple), (int x) -> x*2 (typed).

Block lambda

Multiple statements in lambda body.

passwordToCheck
Block.java
Replay: real traced execution (multi-file project)
import java.util.*;
import java.util.function.*;

public class Block {
    public static void main(String[] args) {
        System.out.println("Single vs block:\n");

        Function<Integer, Integer> single = x -> x * 2;

        Function<Integer, Integer> block = x -> {
            int result = x * 2;
            return result;
        };

        System.out.println("  Single: " + single.apply(5));
        System.out.println("  Block: " + block.apply(5));


        System.out.println("\nComplex logic:");

        Function<Integer, String> classify = n -> {
            if (n < 0) {
                return "negative";
            } else if (n == 0) {
                return "zero";
            } else if (n % 2 == 0) {
                return "positive even";
            } else {
                return "positive odd";
            }
        };

        System.out.println("  classify(-5): " + classify.apply(-5));
        System.out.println("  classify(0): " + classify.apply(0));
        System.out.println("  classify(4): " + classify.apply(4));
        System.out.println("  classify(7): " + classify.apply(7));

        System.out.println("\nLocal variables:");

        BiFunction<Integer, Integer, Integer> gcd = (a, b) -> {
            int temp;
            while (b != 0) {
                temp = b;
                b = a % b;
                a = temp;
            }
            return a;
        };

        System.out.println("  gcd(48, 18) = " + gcd.apply(48, 18));
        System.out.println("  gcd(100, 35) = " + gcd.apply(100, 35));

        System.out.println("\nValidation:");

        Function<String, Boolean> isValidPassword = password -> {
            if (password == null || password.length() < 8) {
                return false;
            }

            boolean hasDigit = false;
            boolean hasLetter = false;

            for (char c : password.toCharArray()) {
                if (Character.isDigit(c)) hasDigit = true;
                if (Character.isLetter(c)) hasLetter = true;
            }

            return hasDigit && hasLetter;
        };

        String passwordToCheck = "abc123def";
        System.out.println("  '" + passwordToCheck + "' valid: " +
                           isValidPassword.apply(passwordToCheck));
        System.out.println("  'short' valid: " + isValidPassword.apply("short"));
        System.out.println("  'onlyletters' valid: " + isValidPassword.apply("onlyletters"));

        System.out.println("\nMulti-step processing:");

        Function<List<Integer>, Double> average = list -> {
            if (list.isEmpty()) {
                return 0.0;
            }

            int sum = 0;
            for (int n : list) {
                sum += n;
            }

            return (double) sum / list.size();
        };

        List<Integer> scores = Arrays.asList(85, 90, 78, 92, 88);
        System.out.println("  Average score: " + average.apply(scores));

        System.out.println("\nException handling:");

        BiFunction<Integer, Integer, Integer> safeDivide = (a, b) -> {
            try {
                return a / b;
            } catch (ArithmeticException e) {
                System.out.println("  Error: " + e.getMessage());
                return 0;
            }
        };

        System.out.println("  10 / 2 = " + safeDivide.apply(10, 2));
        System.out.println("  10 / 0 = " + safeDivide.apply(10, 0));
    }
}
import java.util.*;
import java.util.function.*;

public class Block {
    public static void main(String[] args) {
        System.out.println("Single vs block:\n");

        Function<Integer, Integer> single = x -> x * 2;

        Function<Integer, Integer> block = x -> {
            int result = x * 2;
            return result;
        };

        System.out.println("  Single: " + single.apply(5));
        System.out.println("  Block: " + block.apply(5));


        System.out.println("\nComplex logic:");

        Function<Integer, String> classify = n -> {
            if (n < 0) {
                return "negative";
            } else if (n == 0) {
                return "zero";
            } else if (n % 2 == 0) {
                return "positive even";
            } else {
                return "positive odd";
            }
        };

        System.out.println("  classify(-5): " + classify.apply(-5));
        System.out.println("  classify(0): " + classify.apply(0));
        System.out.println("  classify(4): " + classify.apply(4));
        System.out.println("  classify(7): " + classify.apply(7));

        System.out.println("\nLocal variables:");

        BiFunction<Integer, Integer, Integer> gcd = (a, b) -> {
            int temp;
            while (b != 0) {
                temp = b;
                b = a % b;
                a = temp;
            }
            return a;
        };

        System.out.println("  gcd(48, 18) = " + gcd.apply(48, 18));
        System.out.println("  gcd(100, 35) = " + gcd.apply(100, 35));

        System.out.println("\nValidation:");

        Function<String, Boolean> isValidPassword = password -> {
            if (password == null || password.length() < 8) {
                return false;
            }

            boolean hasDigit = false;
            boolean hasLetter = false;

            for (char c : password.toCharArray()) {
                if (Character.isDigit(c)) hasDigit = true;
                if (Character.isLetter(c)) hasLetter = true;
            }

            return hasDigit && hasLetter;
        };

        String passwordToCheck = "short";
        System.out.println("  '" + passwordToCheck + "' valid: " +
                           isValidPassword.apply(passwordToCheck));
        System.out.println("  'short' valid: " + isValidPassword.apply("short"));
        System.out.println("  'onlyletters' valid: " + isValidPassword.apply("onlyletters"));

        System.out.println("\nMulti-step processing:");

        Function<List<Integer>, Double> average = list -> {
            if (list.isEmpty()) {
                return 0.0;
            }

            int sum = 0;
            for (int n : list) {
                sum += n;
            }

            return (double) sum / list.size();
        };

        List<Integer> scores = Arrays.asList(85, 90, 78, 92, 88);
        System.out.println("  Average score: " + average.apply(scores));

        System.out.println("\nException handling:");

        BiFunction<Integer, Integer, Integer> safeDivide = (a, b) -> {
            try {
                return a / b;
            } catch (ArithmeticException e) {
                System.out.println("  Error: " + e.getMessage());
                return 0;
            }
        };

        System.out.println("  10 / 2 = " + safeDivide.apply(10, 2));
        System.out.println("  10 / 0 = " + safeDivide.apply(10, 0));
    }
}
import java.util.*;
import java.util.function.*;

public class Block {
    public static void main(String[] args) {
        System.out.println("Single vs block:\n");

        Function<Integer, Integer> single = x -> x * 2;

        Function<Integer, Integer> block = x -> {
            int result = x * 2;
            return result;
        };

        System.out.println("  Single: " + single.apply(5));
        System.out.println("  Block: " + block.apply(5));


        System.out.println("\nComplex logic:");

        Function<Integer, String> classify = n -> {
            if (n < 0) {
                return "negative";
            } else if (n == 0) {
                return "zero";
            } else if (n % 2 == 0) {
                return "positive even";
            } else {
                return "positive odd";
            }
        };

        System.out.println("  classify(-5): " + classify.apply(-5));
        System.out.println("  classify(0): " + classify.apply(0));
        System.out.println("  classify(4): " + classify.apply(4));
        System.out.println("  classify(7): " + classify.apply(7));

        System.out.println("\nLocal variables:");

        BiFunction<Integer, Integer, Integer> gcd = (a, b) -> {
            int temp;
            while (b != 0) {
                temp = b;
                b = a % b;
                a = temp;
            }
            return a;
        };

        System.out.println("  gcd(48, 18) = " + gcd.apply(48, 18));
        System.out.println("  gcd(100, 35) = " + gcd.apply(100, 35));

        System.out.println("\nValidation:");

        Function<String, Boolean> isValidPassword = password -> {
            if (password == null || password.length() < 8) {
                return false;
            }

            boolean hasDigit = false;
            boolean hasLetter = false;

            for (char c : password.toCharArray()) {
                if (Character.isDigit(c)) hasDigit = true;
                if (Character.isLetter(c)) hasLetter = true;
            }

            return hasDigit && hasLetter;
        };

        String passwordToCheck = "onlyletters";
        System.out.println("  '" + passwordToCheck + "' valid: " +
                           isValidPassword.apply(passwordToCheck));
        System.out.println("  'short' valid: " + isValidPassword.apply("short"));
        System.out.println("  'onlyletters' valid: " + isValidPassword.apply("onlyletters"));

        System.out.println("\nMulti-step processing:");

        Function<List<Integer>, Double> average = list -> {
            if (list.isEmpty()) {
                return 0.0;
            }

            int sum = 0;
            for (int n : list) {
                sum += n;
            }

            return (double) sum / list.size();
        };

        List<Integer> scores = Arrays.asList(85, 90, 78, 92, 88);
        System.out.println("  Average score: " + average.apply(scores));

        System.out.println("\nException handling:");

        BiFunction<Integer, Integer, Integer> safeDivide = (a, b) -> {
            try {
                return a / b;
            } catch (ArithmeticException e) {
                System.out.println("  Error: " + e.getMessage());
                return 0;
            }
        };

        System.out.println("  10 / 2 = " + safeDivide.apply(10, 2));
        System.out.println("  10 / 0 = " + safeDivide.apply(10, 0));
    }
}
  1. single ← ⟨Block lambda A⟩, block ← ⟨Block lambda B⟩

    4public class Block {5    public static void main(String[] args) {6        System.out.println("Single vs block:\n");7        8        Function<Integer, Integer> single→ ⟨Block lambda A⟩ = x -> x * 2;9        10        Function<Integer, Integer> block→ ⟨Block lambda B⟩ = x -> {11            int result = x * 2;12            return result;13        };14        15        System.out.println("  Single: " + single.apply(5));16        System.out.println("  Block: " + block.apply(5));
    outputSingle vs block:
      Single: 10
  2. classify ← ⟨Block lambda C⟩

    15System.out.println("  Single: " + single.apply(5));16System.out.println("  Block: " + block.apply(5));171819System.out.println("\nComplex logic:");2021Function<Integer, String> classify→ ⟨Block lambda C⟩ = n -> {22    if (n < 0) {23        return "negative";24    } else if (n == 0) {25        return "zero";26    } else if (n % 2 == 0) {27        return "positive even";28    } else {29        return "positive odd";30    }31};3233System.out.println("  classify(-5): " + classify.apply(-5));34System.out.println("  classify(0): " + classify.apply(0));
    output  Block: 10
    
    Complex logic:
  3. System.out.println(" classify(-5): " + classify.apply(-5));

    33System.out.println("  classify(-5): " + classify.apply(-5));34System.out.println("  classify(0): " + classify.apply(0));35System.out.println("  classify(4): " + classify.apply(4));
    output  classify(-5): negative
  4. System.out.println(" classify(0): " + classify.apply(0));

    33System.out.println("  classify(-5): " + classify.apply(-5));34System.out.println("  classify(0): " + classify.apply(0));35System.out.println("  classify(4): " + classify.apply(4));36System.out.println("  classify(7): " + classify.apply(7));
    output  classify(0): zero
  5. System.out.println(" classify(4): " + classify.apply(4));

    34System.out.println("  classify(0): " + classify.apply(0));35System.out.println("  classify(4): " + classify.apply(4));36System.out.println("  classify(7): " + classify.apply(7));
    output  classify(4): positive even
  6. gcd ← ⟨Block lambda D⟩

    35System.out.println("  classify(4): " + classify.apply(4));36System.out.println("  classify(7): " + classify.apply(7));3738System.out.println("\nLocal variables:");3940BiFunction<Integer, Integer, Integer> gcd→ ⟨Block lambda D⟩ = (a, b) -> {41    int temp;42    while (b != 0) {43        temp = b;44        b = a % b;45        a = temp;46    }47    return a;48};4950System.out.println("  gcd(48, 18) = " + gcd.apply(48, 18));51System.out.println("  gcd(100, 35) = " + gcd.apply(100, 35));
    output  classify(7): positive odd
    
    Local variables:
  7. return a;

    46    }47    return a;48};
  8. System.out.println(" gcd(48, 18) = " + gcd.apply(48, 18));

    50System.out.println("  gcd(48, 18) = " + gcd.apply(48, 18));51System.out.println("  gcd(100, 35) = " + gcd.apply(100, 35));
    output  gcd(48, 18) = 6
  9. return a;

    46    }47    return a;48};
  10. isValidPassword ← ⟨Block lambda E⟩, passwordToCheck ← abc123def

    50System.out.println("  gcd(48, 18) = " + gcd.apply(48, 18));51System.out.println("  gcd(100, 35) = " + gcd.apply(100, 35));5253System.out.println("\nValidation:");5455Function<String, Boolean> isValidPassword→ ⟨Block lambda E⟩ = password -> {56    if (password == null || password.length() < 8) {57        return false;58    }59    60    boolean hasDigit = false;61    boolean hasLetter = false;62    63    for (char c : password.toCharArray()) {64        if (Character.isDigit(c)) hasDigit = true;65        if (Character.isLetter(c)) hasLetter = true;66    }67    68    return hasDigit && hasLetter;69};7071String passwordToCheck→ abc123def = "abc123def"; //@passwordToCheck="abc123def", "short", "onlyletters"72System.out.println("  '" + passwordToCheckabc123def + "' valid: " +73                   isValidPassword.apply(passwordToCheckabc123def));74System.out.println("  'short' valid: " + isValidPassword.apply("short"));
    output  gcd(100, 35) = 5
    
    Validation:
  11. return hasDigit && hasLetter;

    68    return hasDigit && hasLetter;69};
  12. System.out.println(" '" + passwordToCheck + "' valid: " +

    71String passwordToCheck = "abc123def"; //@passwordToCheck="abc123def", "short", "onlyletters"72System.out.println("  '" + passwordToCheckabc123def + "' valid: " +73                   isValidPassword.apply(passwordToCheckabc123def));74System.out.println("  'short' valid: " + isValidPassword.apply("short"));75System.out.println("  'onlyletters' valid: " + isValidPassword.apply("onlyletters"));
    output  'abc123def' valid: true
  13. System.out.println(" 'short' valid: " + isValidPassword.apply("short"…

    73                   isValidPassword.apply(passwordToCheck));74System.out.println("  'short' valid: " + isValidPassword.apply("short"));75System.out.println("  'onlyletters' valid: " + isValidPassword.apply("onlyletters"));
    output  'short' valid: false
  14. return hasDigit && hasLetter;

    68    return hasDigit && hasLetter;69};
  15. average ← ⟨Block lambda F⟩, scores ← [85, 90, 78, 92, 88]

    74System.out.println("  'short' valid: " + isValidPassword.apply("short"));75System.out.println("  'onlyletters' valid: " + isValidPassword.apply("onlyletters"));7677System.out.println("\nMulti-step processing:");7879Function<List<Integer>, Double> average→ ⟨Block lambda F⟩ = list -> {80    if (list.isEmpty()) {81        return 0.0;82    }83    84    int sum = 0;85    for (int n : list) {86        sum += n;87    }88    89    return (double) sum / list.size();90};9192List<Integer> scores→ [85, 90, 78, 92, 88] = Arrays.asList(85, 90, 78, 92, 88);93System.out.println("  Average score: " + average.apply(scores[85, 90, 78, 92, 88]));
    output  'onlyletters' valid: false
    
    Multi-step processing:
  16. return (double) sum / list.size();

    89    return (double) sum / list.size();90};
  17. safeDivide ← ⟨Block lambda G⟩

    92List<Integer> scores = Arrays.asList(85, 90, 78, 92, 88);93System.out.println("  Average score: " + average.apply(scores[85, 90, 78, 92, 88]));9495System.out.println("\nException handling:");9697BiFunction<Integer, Integer, Integer> safeDivide→ ⟨Block lambda G⟩ = (a, b) -> {98    try {99        return a / b;100    } catch (ArithmeticException e) {101        System.out.println("  Error: " + e.getMessage());102        return 0;103    }104};105106System.out.println("  10 / 2 = " + safeDivide.apply(10, 2));107System.out.println("  10 / 0 = " + safeDivide.apply(10, 0));
    output  Average score: 86.6
    
    Exception handling:
  18. System.out.println(" 10 / 2 = " + safeDivide.apply(10, 2));

    106    System.out.println("  10 / 2 = " + safeDivide.apply(10, 2));107    System.out.println("  10 / 0 = " + safeDivide.apply(10, 0));108}
    output  10 / 2 = 5
  19. catch (ArithmeticException e)

    99    return a / b;100} catch (ArithmeticException e) {101    System.out.println("  Error: " + e.getMessage());102    return 0;103}
    output  Error: / by zero
  20. System.out.println(" 10 / 0 = " + safeDivide.apply(10, 0));

    106    System.out.println("  10 / 2 = " + safeDivide.apply(10, 2));107    System.out.println("  10 / 0 = " + safeDivide.apply(10, 0));108}
    output  10 / 0 = 0
  1. single ← ⟨Block lambda A⟩, block ← ⟨Block lambda B⟩

    4public class Block {5    public static void main(String[] args) {6        System.out.println("Single vs block:\n");7        8        Function<Integer, Integer> single→ ⟨Block lambda A⟩ = x -> x * 2;9        10        Function<Integer, Integer> block→ ⟨Block lambda B⟩ = x -> {11            int result = x * 2;12            return result;13        };14        15        System.out.println("  Single: " + single.apply(5));16        System.out.println("  Block: " + block.apply(5));
    outputSingle vs block:
      Single: 10
  2. classify ← ⟨Block lambda C⟩

    15System.out.println("  Single: " + single.apply(5));16System.out.println("  Block: " + block.apply(5));171819System.out.println("\nComplex logic:");2021Function<Integer, String> classify→ ⟨Block lambda C⟩ = n -> {22    if (n < 0) {23        return "negative";24    } else if (n == 0) {25        return "zero";26    } else if (n % 2 == 0) {27        return "positive even";28    } else {29        return "positive odd";30    }31};3233System.out.println("  classify(-5): " + classify.apply(-5));34System.out.println("  classify(0): " + classify.apply(0));
    output  Block: 10
    
    Complex logic:
  3. System.out.println(" classify(-5): " + classify.apply(-5));

    33System.out.println("  classify(-5): " + classify.apply(-5));34System.out.println("  classify(0): " + classify.apply(0));35System.out.println("  classify(4): " + classify.apply(4));
    output  classify(-5): negative
  4. System.out.println(" classify(0): " + classify.apply(0));

    33System.out.println("  classify(-5): " + classify.apply(-5));34System.out.println("  classify(0): " + classify.apply(0));35System.out.println("  classify(4): " + classify.apply(4));36System.out.println("  classify(7): " + classify.apply(7));
    output  classify(0): zero
  5. System.out.println(" classify(4): " + classify.apply(4));

    34System.out.println("  classify(0): " + classify.apply(0));35System.out.println("  classify(4): " + classify.apply(4));36System.out.println("  classify(7): " + classify.apply(7));
    output  classify(4): positive even
  6. gcd ← ⟨Block lambda D⟩

    35System.out.println("  classify(4): " + classify.apply(4));36System.out.println("  classify(7): " + classify.apply(7));3738System.out.println("\nLocal variables:");3940BiFunction<Integer, Integer, Integer> gcd→ ⟨Block lambda D⟩ = (a, b) -> {41    int temp;42    while (b != 0) {43        temp = b;44        b = a % b;45        a = temp;46    }47    return a;48};4950System.out.println("  gcd(48, 18) = " + gcd.apply(48, 18));51System.out.println("  gcd(100, 35) = " + gcd.apply(100, 35));
    output  classify(7): positive odd
    
    Local variables:
  7. return a;

    46    }47    return a;48};
  8. System.out.println(" gcd(48, 18) = " + gcd.apply(48, 18));

    50System.out.println("  gcd(48, 18) = " + gcd.apply(48, 18));51System.out.println("  gcd(100, 35) = " + gcd.apply(100, 35));
    output  gcd(48, 18) = 6
  9. return a;

    46    }47    return a;48};
  10. isValidPassword ← ⟨Block lambda E⟩, passwordToCheck ← short

    50System.out.println("  gcd(48, 18) = " + gcd.apply(48, 18));51System.out.println("  gcd(100, 35) = " + gcd.apply(100, 35));5253System.out.println("\nValidation:");5455Function<String, Boolean> isValidPassword→ ⟨Block lambda E⟩ = password -> {56    if (password == null || password.length() < 8) {57        return false;58    }59    60    boolean hasDigit = false;61    boolean hasLetter = false;62    63    for (char c : password.toCharArray()) {64        if (Character.isDigit(c)) hasDigit = true;65        if (Character.isLetter(c)) hasLetter = true;66    }67    68    return hasDigit && hasLetter;69};7071String passwordToCheck→ short = "short";72System.out.println("  '" + passwordToCheckshort + "' valid: " +73                   isValidPassword.apply(passwordToCheckshort));74System.out.println("  'short' valid: " + isValidPassword.apply("short"));
    output  gcd(100, 35) = 5
    
    Validation:
  11. System.out.println(" '" + passwordToCheck + "' valid: " +

    71String passwordToCheck = "short";72System.out.println("  '" + passwordToCheckshort + "' valid: " +73                   isValidPassword.apply(passwordToCheckshort));74System.out.println("  'short' valid: " + isValidPassword.apply("short"));75System.out.println("  'onlyletters' valid: " + isValidPassword.apply("onlyletters"));
    output  'short' valid: false
  12. System.out.println(" 'short' valid: " + isValidPassword.apply("short"…

    73                   isValidPassword.apply(passwordToCheck));74System.out.println("  'short' valid: " + isValidPassword.apply("short"));75System.out.println("  'onlyletters' valid: " + isValidPassword.apply("onlyletters"));
    output  'short' valid: false
  13. return hasDigit && hasLetter;

    68    return hasDigit && hasLetter;69};
  14. average ← ⟨Block lambda F⟩, scores ← [85, 90, 78, 92, 88]

    74System.out.println("  'short' valid: " + isValidPassword.apply("short"));75System.out.println("  'onlyletters' valid: " + isValidPassword.apply("onlyletters"));7677System.out.println("\nMulti-step processing:");7879Function<List<Integer>, Double> average→ ⟨Block lambda F⟩ = list -> {80    if (list.isEmpty()) {81        return 0.0;82    }83    84    int sum = 0;85    for (int n : list) {86        sum += n;87    }88    89    return (double) sum / list.size();90};9192List<Integer> scores→ [85, 90, 78, 92, 88] = Arrays.asList(85, 90, 78, 92, 88);93System.out.println("  Average score: " + average.apply(scores[85, 90, 78, 92, 88]));
    output  'onlyletters' valid: false
    
    Multi-step processing:
  15. return (double) sum / list.size();

    89    return (double) sum / list.size();90};
  16. safeDivide ← ⟨Block lambda G⟩

    92List<Integer> scores = Arrays.asList(85, 90, 78, 92, 88);93System.out.println("  Average score: " + average.apply(scores[85, 90, 78, 92, 88]));9495System.out.println("\nException handling:");9697BiFunction<Integer, Integer, Integer> safeDivide→ ⟨Block lambda G⟩ = (a, b) -> {98    try {99        return a / b;100    } catch (ArithmeticException e) {101        System.out.println("  Error: " + e.getMessage());102        return 0;103    }104};105106System.out.println("  10 / 2 = " + safeDivide.apply(10, 2));107System.out.println("  10 / 0 = " + safeDivide.apply(10, 0));
    output  Average score: 86.6
    
    Exception handling:
  17. System.out.println(" 10 / 2 = " + safeDivide.apply(10, 2));

    106    System.out.println("  10 / 2 = " + safeDivide.apply(10, 2));107    System.out.println("  10 / 0 = " + safeDivide.apply(10, 0));108}
    output  10 / 2 = 5
  18. catch (ArithmeticException e)

    99    return a / b;100} catch (ArithmeticException e) {101    System.out.println("  Error: " + e.getMessage());102    return 0;103}
    output  Error: / by zero
  19. System.out.println(" 10 / 0 = " + safeDivide.apply(10, 0));

    106    System.out.println("  10 / 2 = " + safeDivide.apply(10, 2));107    System.out.println("  10 / 0 = " + safeDivide.apply(10, 0));108}
    output  10 / 0 = 0
  1. single ← ⟨Block lambda A⟩, block ← ⟨Block lambda B⟩

    4public class Block {5    public static void main(String[] args) {6        System.out.println("Single vs block:\n");7        8        Function<Integer, Integer> single→ ⟨Block lambda A⟩ = x -> x * 2;9        10        Function<Integer, Integer> block→ ⟨Block lambda B⟩ = x -> {11            int result = x * 2;12            return result;13        };14        15        System.out.println("  Single: " + single.apply(5));16        System.out.println("  Block: " + block.apply(5));
    outputSingle vs block:
      Single: 10
  2. classify ← ⟨Block lambda C⟩

    15System.out.println("  Single: " + single.apply(5));16System.out.println("  Block: " + block.apply(5));171819System.out.println("\nComplex logic:");2021Function<Integer, String> classify→ ⟨Block lambda C⟩ = n -> {22    if (n < 0) {23        return "negative";24    } else if (n == 0) {25        return "zero";26    } else if (n % 2 == 0) {27        return "positive even";28    } else {29        return "positive odd";30    }31};3233System.out.println("  classify(-5): " + classify.apply(-5));34System.out.println("  classify(0): " + classify.apply(0));
    output  Block: 10
    
    Complex logic:
  3. System.out.println(" classify(-5): " + classify.apply(-5));

    33System.out.println("  classify(-5): " + classify.apply(-5));34System.out.println("  classify(0): " + classify.apply(0));35System.out.println("  classify(4): " + classify.apply(4));
    output  classify(-5): negative
  4. System.out.println(" classify(0): " + classify.apply(0));

    33System.out.println("  classify(-5): " + classify.apply(-5));34System.out.println("  classify(0): " + classify.apply(0));35System.out.println("  classify(4): " + classify.apply(4));36System.out.println("  classify(7): " + classify.apply(7));
    output  classify(0): zero
  5. System.out.println(" classify(4): " + classify.apply(4));

    34System.out.println("  classify(0): " + classify.apply(0));35System.out.println("  classify(4): " + classify.apply(4));36System.out.println("  classify(7): " + classify.apply(7));
    output  classify(4): positive even
  6. gcd ← ⟨Block lambda D⟩

    35System.out.println("  classify(4): " + classify.apply(4));36System.out.println("  classify(7): " + classify.apply(7));3738System.out.println("\nLocal variables:");3940BiFunction<Integer, Integer, Integer> gcd→ ⟨Block lambda D⟩ = (a, b) -> {41    int temp;42    while (b != 0) {43        temp = b;44        b = a % b;45        a = temp;46    }47    return a;48};4950System.out.println("  gcd(48, 18) = " + gcd.apply(48, 18));51System.out.println("  gcd(100, 35) = " + gcd.apply(100, 35));
    output  classify(7): positive odd
    
    Local variables:
  7. return a;

    46    }47    return a;48};
  8. System.out.println(" gcd(48, 18) = " + gcd.apply(48, 18));

    50System.out.println("  gcd(48, 18) = " + gcd.apply(48, 18));51System.out.println("  gcd(100, 35) = " + gcd.apply(100, 35));
    output  gcd(48, 18) = 6
  9. return a;

    46    }47    return a;48};
  10. isValidPassword ← ⟨Block lambda E⟩, passwordToCheck ← onlyletters

    50System.out.println("  gcd(48, 18) = " + gcd.apply(48, 18));51System.out.println("  gcd(100, 35) = " + gcd.apply(100, 35));5253System.out.println("\nValidation:");5455Function<String, Boolean> isValidPassword→ ⟨Block lambda E⟩ = password -> {56    if (password == null || password.length() < 8) {57        return false;58    }59    60    boolean hasDigit = false;61    boolean hasLetter = false;62    63    for (char c : password.toCharArray()) {64        if (Character.isDigit(c)) hasDigit = true;65        if (Character.isLetter(c)) hasLetter = true;66    }67    68    return hasDigit && hasLetter;69};7071String passwordToCheck→ onlyletters = "onlyletters";72System.out.println("  '" + passwordToCheckonlyletters + "' valid: " +73                   isValidPassword.apply(passwordToCheckonlyletters));74System.out.println("  'short' valid: " + isValidPassword.apply("short"));
    output  gcd(100, 35) = 5
    
    Validation:
  11. return hasDigit && hasLetter;

    68    return hasDigit && hasLetter;69};
  12. System.out.println(" '" + passwordToCheck + "' valid: " +

    71String passwordToCheck = "onlyletters";72System.out.println("  '" + passwordToCheckonlyletters + "' valid: " +73                   isValidPassword.apply(passwordToCheckonlyletters));74System.out.println("  'short' valid: " + isValidPassword.apply("short"));75System.out.println("  'onlyletters' valid: " + isValidPassword.apply("onlyletters"));
    output  'onlyletters' valid: false
  13. System.out.println(" 'short' valid: " + isValidPassword.apply("short"…

    73                   isValidPassword.apply(passwordToCheck));74System.out.println("  'short' valid: " + isValidPassword.apply("short"));75System.out.println("  'onlyletters' valid: " + isValidPassword.apply("onlyletters"));
    output  'short' valid: false
  14. return hasDigit && hasLetter;

    68    return hasDigit && hasLetter;69};
  15. average ← ⟨Block lambda F⟩, scores ← [85, 90, 78, 92, 88]

    74System.out.println("  'short' valid: " + isValidPassword.apply("short"));75System.out.println("  'onlyletters' valid: " + isValidPassword.apply("onlyletters"));7677System.out.println("\nMulti-step processing:");7879Function<List<Integer>, Double> average→ ⟨Block lambda F⟩ = list -> {80    if (list.isEmpty()) {81        return 0.0;82    }83    84    int sum = 0;85    for (int n : list) {86        sum += n;87    }88    89    return (double) sum / list.size();90};9192List<Integer> scores→ [85, 90, 78, 92, 88] = Arrays.asList(85, 90, 78, 92, 88);93System.out.println("  Average score: " + average.apply(scores[85, 90, 78, 92, 88]));
    output  'onlyletters' valid: false
    
    Multi-step processing:
  16. return (double) sum / list.size();

    89    return (double) sum / list.size();90};
  17. safeDivide ← ⟨Block lambda G⟩

    92List<Integer> scores = Arrays.asList(85, 90, 78, 92, 88);93System.out.println("  Average score: " + average.apply(scores[85, 90, 78, 92, 88]));9495System.out.println("\nException handling:");9697BiFunction<Integer, Integer, Integer> safeDivide→ ⟨Block lambda G⟩ = (a, b) -> {98    try {99        return a / b;100    } catch (ArithmeticException e) {101        System.out.println("  Error: " + e.getMessage());102        return 0;103    }104};105106System.out.println("  10 / 2 = " + safeDivide.apply(10, 2));107System.out.println("  10 / 0 = " + safeDivide.apply(10, 0));
    output  Average score: 86.6
    
    Exception handling:
  18. System.out.println(" 10 / 2 = " + safeDivide.apply(10, 2));

    106    System.out.println("  10 / 2 = " + safeDivide.apply(10, 2));107    System.out.println("  10 / 0 = " + safeDivide.apply(10, 0));108}
    output  10 / 2 = 5
  19. catch (ArithmeticException e)

    99    return a / b;100} catch (ArithmeticException e) {101    System.out.println("  Error: " + e.getMessage());102    return 0;103}
    output  Error: / by zero
  20. System.out.println(" 10 / 0 = " + safeDivide.apply(10, 0));

    106    System.out.println("  10 / 2 = " + safeDivide.apply(10, 2));107    System.out.println("  10 / 0 = " + safeDivide.apply(10, 0));108}
    output  10 / 0 = 0

(x) -> { statements; return value; } - braces and return for complex logic.

Effectively final

Lambda can access local variables if effectively final.

multiplier
EffectivelyFinal.java
Replay: real traced execution (multi-file project)
import java.util.*;
import java.util.function.*;

public class EffectivelyFinal {
    public static void main(String[] args) {
        System.out.println("Effectively final:\n");

        int multiplier = 10;

        Function<Integer, Integer> multiply = x -> x * multiplier;

        System.out.println("  5 * 10 = " + multiply.apply(5));
        System.out.println("  7 * 10 = " + multiply.apply(7));



        System.out.println("\nMultiple captures:");

        String prefix = "Value: ";
        String suffix = "!";

        Function<Integer, String> format = n -> prefix + n + suffix;

        System.out.println("  " + format.apply(42));
        System.out.println("  " + format.apply(99));

        System.out.println("\nMethod parameters:");

        processList(Arrays.asList(1, 2, 3, 4, 5), 3);

        System.out.println("\nInstance variables:");

        Counter counter = new Counter();
        counter.demonstrate();

        System.out.println("\nExplicit final:");

        final int factor = 5;

        BinaryOperator<Integer> scale = (a, b) -> (a + b) * factor;

        System.out.println("  (2 + 3) * 5 = " + scale.apply(2, 3));

        System.out.println("\nArray capture:");

        int[] counters = {0};  // Effectively final reference, mutable content

        Runnable increment = () -> counters[0]++;

        increment.run();
        increment.run();
        increment.run();

        System.out.println("  Counter: " + counters[0]);
    }

    static void processList(List<Integer> numbers, int threshold) {
        numbers.forEach(n -> {
            if (n > threshold) {
                System.out.println("  " + n + " exceeds " + threshold);
            }
        });
    }
}

class Counter {
    private int count = 0;

    void demonstrate() {
        Runnable inc = () -> count++;

        inc.run();
        inc.run();
        inc.run();

        System.out.println("  Count: " + count);

        Supplier<Integer> getCount = () -> this.count;
        System.out.println("  Get count: " + getCount.get());
    }
}
import java.util.*;
import java.util.function.*;

public class EffectivelyFinal {
    public static void main(String[] args) {
        System.out.println("Effectively final:\n");

        int multiplier = 3;

        Function<Integer, Integer> multiply = x -> x * multiplier;

        System.out.println("  5 * 10 = " + multiply.apply(5));
        System.out.println("  7 * 10 = " + multiply.apply(7));



        System.out.println("\nMultiple captures:");

        String prefix = "Value: ";
        String suffix = "!";

        Function<Integer, String> format = n -> prefix + n + suffix;

        System.out.println("  " + format.apply(42));
        System.out.println("  " + format.apply(99));

        System.out.println("\nMethod parameters:");

        processList(Arrays.asList(1, 2, 3, 4, 5), 3);

        System.out.println("\nInstance variables:");

        Counter counter = new Counter();
        counter.demonstrate();

        System.out.println("\nExplicit final:");

        final int factor = 5;

        BinaryOperator<Integer> scale = (a, b) -> (a + b) * factor;

        System.out.println("  (2 + 3) * 5 = " + scale.apply(2, 3));

        System.out.println("\nArray capture:");

        int[] counters = {0};  // Effectively final reference, mutable content

        Runnable increment = () -> counters[0]++;

        increment.run();
        increment.run();
        increment.run();

        System.out.println("  Counter: " + counters[0]);
    }

    static void processList(List<Integer> numbers, int threshold) {
        numbers.forEach(n -> {
            if (n > threshold) {
                System.out.println("  " + n + " exceeds " + threshold);
            }
        });
    }
}

class Counter {
    private int count = 0;

    void demonstrate() {
        Runnable inc = () -> count++;

        inc.run();
        inc.run();
        inc.run();

        System.out.println("  Count: " + count);

        Supplier<Integer> getCount = () -> this.count;
        System.out.println("  Get count: " + getCount.get());
    }
}
import java.util.*;
import java.util.function.*;

public class EffectivelyFinal {
    public static void main(String[] args) {
        System.out.println("Effectively final:\n");

        int multiplier = 20;

        Function<Integer, Integer> multiply = x -> x * multiplier;

        System.out.println("  5 * 10 = " + multiply.apply(5));
        System.out.println("  7 * 10 = " + multiply.apply(7));



        System.out.println("\nMultiple captures:");

        String prefix = "Value: ";
        String suffix = "!";

        Function<Integer, String> format = n -> prefix + n + suffix;

        System.out.println("  " + format.apply(42));
        System.out.println("  " + format.apply(99));

        System.out.println("\nMethod parameters:");

        processList(Arrays.asList(1, 2, 3, 4, 5), 3);

        System.out.println("\nInstance variables:");

        Counter counter = new Counter();
        counter.demonstrate();

        System.out.println("\nExplicit final:");

        final int factor = 5;

        BinaryOperator<Integer> scale = (a, b) -> (a + b) * factor;

        System.out.println("  (2 + 3) * 5 = " + scale.apply(2, 3));

        System.out.println("\nArray capture:");

        int[] counters = {0};  // Effectively final reference, mutable content

        Runnable increment = () -> counters[0]++;

        increment.run();
        increment.run();
        increment.run();

        System.out.println("  Counter: " + counters[0]);
    }

    static void processList(List<Integer> numbers, int threshold) {
        numbers.forEach(n -> {
            if (n > threshold) {
                System.out.println("  " + n + " exceeds " + threshold);
            }
        });
    }
}

class Counter {
    private int count = 0;

    void demonstrate() {
        Runnable inc = () -> count++;

        inc.run();
        inc.run();
        inc.run();

        System.out.println("  Count: " + count);

        Supplier<Integer> getCount = () -> this.count;
        System.out.println("  Get count: " + getCount.get());
    }
}
  1. multiplier ← 10, multiply ← ⟨EffectivelyFinal lambda A⟩, prefix ← Value:

    4public class EffectivelyFinal {5    public static void main(String[] args) {6        System.out.println("Effectively final:\n");7        8        int multiplier→ 10 = 10; //@multiplier=10, 3, 209        10        Function<Integer, Integer> multiply→ ⟨EffectivelyFinal lambda A⟩ = x -> x * multiplier;11        12        System.out.println("  5 * 10 = " + multiply.apply(5));13        System.out.println("  7 * 10 = " + multiply.apply(7));14        15        16        17        System.out.println("\nMultiple captures:");18        19        String prefix→ Value:  = "Value: ";20        String suffix→ ! = "!";21        22        Function<Integer, String> format→ ⟨EffectivelyFinal lambda B⟩ = n -> prefix + n + suffix;23        24        System.out.println("  " + format.apply(42));25        System.out.println("  " + format.apply(99));26        27        System.out.println("\nMethod parameters:");28        29        processList(Arrays.asList(1, 2, 3, 4, 5), 3);
    outputEffectively final:
      5 * 10 = 50
      7 * 10 = 70
    
    Multiple captures:
      Value: 42!
      Value: 99!
    
    Method parameters:
  2. static void processList(List<Integer> numbers, int threshold)

    57static void processList(List<Integer> numbers[1, 2, 3, 4, 5], int threshold3) {58    numbers.forEach(n -> {59        if (n > threshold) {60            System.out.println("  " + n + " exceeds " + threshold);61        }62    });63}
  3. n ->

    pass 1 of 5
    57static void processList(List<Integer> numbers, int threshold) {58    numbers.forEach(n -> {59        if (n > threshold) {
    All 5 passes — pass 1 is the card above
    passcountcounters[0]counterincgetCountfactorscaleincrement
    1
    2
    3
    4
    533⟨Counter C⟩⟨Counter lambda D⟩⟨Counter lambda E⟩5⟨EffectivelyFinal lambda F⟩⟨EffectivelyFinal lambda G⟩
  4. if (n > threshold)

    pass 1 of 2
    58numbers.forEach(n -> {59    if (n > threshold) {60        System.out.println("  " + n + " exceeds " + threshold);61    }
    output  4 exceeds 3
  5. counter ← ⟨Counter C⟩

    pass 2 of 2
    29    processList(Arrays.asList(1, 2, 3, 4, 5), 3);30    31    System.out.println("\nInstance variables:");32    33    Counter counter→ ⟨Counter C⟩ = new Counter();34    counter.demonstrate();35    36    System.out.println("\nExplicit final:");37    38    final int factor = 5;39    40    BinaryOperator<Integer> scale = (a, b) -> (a + b) * factor;41    42    System.out.println("  (2 + 3) * 5 = " + scale.apply(2, 3));43    44    System.out.println("\nArray capture:");45    46    int[] counters = {0};  // Effectively final reference, mutable content47    48    Runnable increment = () -> counters[0]++;49    50    increment.run();51    increment.run();52    increment.run();53    54    System.out.println("  Counter: " + counters[0]);55}5657static void processList(List<Integer> numbers, int threshold) {58    numbers.forEach(n -> {59        if (n > threshold) {60            System.out.println("  " + n + " exceeds " + threshold);61        }62    });63}
    output  5 exceeds 3
    
    Instance variables:
  6. inc ← ⟨Counter lambda D⟩, getCount ← ⟨Counter lambda E⟩, factor ← 5

    33        Counter counter = new Counter();34        counter.demonstrate();35        36        System.out.println("\nExplicit final:");37        38        final int factor→ 5 = 5;39        40        BinaryOperator<Integer> scale→ ⟨EffectivelyFinal lambda F⟩ = (a, b) -> (a + b) * factor;41        42        System.out.println("  (2 + 3) * 5 = " + scale.apply(2, 3));43        44        System.out.println("\nArray capture:");45        46        int[] counters = {0};  // Effectively final reference, mutable content47        48        Runnable increment→ ⟨EffectivelyFinal lambda G⟩ = () -> counters[0]++;49        50        increment.run();51        increment.run();52        increment.run();53        54        System.out.println("  Counter: " + counters[0]3);55    }56    57    static void processList(List<Integer> numbers, int threshold) {58        numbers.forEach(n -> {59            if (n > threshold) {60                System.out.println("  " + n + " exceeds " + threshold);61            }62        });63    }64}6566class Counter {67    private int count = 0;68    69    void demonstrate() {70        Runnable inc→ ⟨Counter lambda D⟩ = () -> count++;71        72        inc.run();73        inc.run();74        inc.run();75        76        System.out.println("  Count: " + count3);77        78        Supplier<Integer> getCount→ ⟨Counter lambda E⟩ = () -> this.count;79        System.out.println("  Get count: " + getCount.get());80    }
    output  Count: 3
      Get count: 3
    
    Explicit final:
      (2 + 3) * 5 = 25
    
    Array capture:
      Counter: 3
  1. multiplier ← 3, multiply ← ⟨EffectivelyFinal lambda A⟩, prefix ← Value:

    4public class EffectivelyFinal {5    public static void main(String[] args) {6        System.out.println("Effectively final:\n");7        8        int multiplier→ 3 = 3;9        10        Function<Integer, Integer> multiply→ ⟨EffectivelyFinal lambda A⟩ = x -> x * multiplier;11        12        System.out.println("  5 * 10 = " + multiply.apply(5));13        System.out.println("  7 * 10 = " + multiply.apply(7));14        15        16        17        System.out.println("\nMultiple captures:");18        19        String prefix→ Value:  = "Value: ";20        String suffix→ ! = "!";21        22        Function<Integer, String> format→ ⟨EffectivelyFinal lambda B⟩ = n -> prefix + n + suffix;23        24        System.out.println("  " + format.apply(42));25        System.out.println("  " + format.apply(99));26        27        System.out.println("\nMethod parameters:");28        29        processList(Arrays.asList(1, 2, 3, 4, 5), 3);
    outputEffectively final:
      5 * 10 = 15
      7 * 10 = 21
    
    Multiple captures:
      Value: 42!
      Value: 99!
    
    Method parameters:
  2. static void processList(List<Integer> numbers, int threshold)

    57static void processList(List<Integer> numbers[1, 2, 3, 4, 5], int threshold3) {58    numbers.forEach(n -> {59        if (n > threshold) {60            System.out.println("  " + n + " exceeds " + threshold);61        }62    });63}
  3. n ->

    pass 1 of 5
    57static void processList(List<Integer> numbers, int threshold) {58    numbers.forEach(n -> {59        if (n > threshold) {
    All 5 passes — pass 1 is the card above
    passcountcounters[0]counterincgetCountfactorscaleincrement
    1
    2
    3
    4
    533⟨Counter C⟩⟨Counter lambda D⟩⟨Counter lambda E⟩5⟨EffectivelyFinal lambda F⟩⟨EffectivelyFinal lambda G⟩
  4. if (n > threshold)

    pass 1 of 2
    58numbers.forEach(n -> {59    if (n > threshold) {60        System.out.println("  " + n + " exceeds " + threshold);61    }
    output  4 exceeds 3
  5. counter ← ⟨Counter C⟩

    pass 2 of 2
    29    processList(Arrays.asList(1, 2, 3, 4, 5), 3);30    31    System.out.println("\nInstance variables:");32    33    Counter counter→ ⟨Counter C⟩ = new Counter();34    counter.demonstrate();35    36    System.out.println("\nExplicit final:");37    38    final int factor = 5;39    40    BinaryOperator<Integer> scale = (a, b) -> (a + b) * factor;41    42    System.out.println("  (2 + 3) * 5 = " + scale.apply(2, 3));43    44    System.out.println("\nArray capture:");45    46    int[] counters = {0};  // Effectively final reference, mutable content47    48    Runnable increment = () -> counters[0]++;49    50    increment.run();51    increment.run();52    increment.run();53    54    System.out.println("  Counter: " + counters[0]);55}5657static void processList(List<Integer> numbers, int threshold) {58    numbers.forEach(n -> {59        if (n > threshold) {60            System.out.println("  " + n + " exceeds " + threshold);61        }62    });63}
    output  5 exceeds 3
    
    Instance variables:
  6. inc ← ⟨Counter lambda D⟩, getCount ← ⟨Counter lambda E⟩, factor ← 5

    33        Counter counter = new Counter();34        counter.demonstrate();35        36        System.out.println("\nExplicit final:");37        38        final int factor→ 5 = 5;39        40        BinaryOperator<Integer> scale→ ⟨EffectivelyFinal lambda F⟩ = (a, b) -> (a + b) * factor;41        42        System.out.println("  (2 + 3) * 5 = " + scale.apply(2, 3));43        44        System.out.println("\nArray capture:");45        46        int[] counters = {0};  // Effectively final reference, mutable content47        48        Runnable increment→ ⟨EffectivelyFinal lambda G⟩ = () -> counters[0]++;49        50        increment.run();51        increment.run();52        increment.run();53        54        System.out.println("  Counter: " + counters[0]3);55    }56    57    static void processList(List<Integer> numbers, int threshold) {58        numbers.forEach(n -> {59            if (n > threshold) {60                System.out.println("  " + n + " exceeds " + threshold);61            }62        });63    }64}6566class Counter {67    private int count = 0;68    69    void demonstrate() {70        Runnable inc→ ⟨Counter lambda D⟩ = () -> count++;71        72        inc.run();73        inc.run();74        inc.run();75        76        System.out.println("  Count: " + count3);77        78        Supplier<Integer> getCount→ ⟨Counter lambda E⟩ = () -> this.count;79        System.out.println("  Get count: " + getCount.get());80    }
    output  Count: 3
      Get count: 3
    
    Explicit final:
      (2 + 3) * 5 = 25
    
    Array capture:
      Counter: 3
  1. multiplier ← 20, multiply ← ⟨EffectivelyFinal lambda A⟩, prefix ← Value:

    4public class EffectivelyFinal {5    public static void main(String[] args) {6        System.out.println("Effectively final:\n");7        8        int multiplier→ 20 = 20;9        10        Function<Integer, Integer> multiply→ ⟨EffectivelyFinal lambda A⟩ = x -> x * multiplier;11        12        System.out.println("  5 * 10 = " + multiply.apply(5));13        System.out.println("  7 * 10 = " + multiply.apply(7));14        15        16        17        System.out.println("\nMultiple captures:");18        19        String prefix→ Value:  = "Value: ";20        String suffix→ ! = "!";21        22        Function<Integer, String> format→ ⟨EffectivelyFinal lambda B⟩ = n -> prefix + n + suffix;23        24        System.out.println("  " + format.apply(42));25        System.out.println("  " + format.apply(99));26        27        System.out.println("\nMethod parameters:");28        29        processList(Arrays.asList(1, 2, 3, 4, 5), 3);
    outputEffectively final:
      5 * 10 = 100
      7 * 10 = 140
    
    Multiple captures:
      Value: 42!
      Value: 99!
    
    Method parameters:
  2. static void processList(List<Integer> numbers, int threshold)

    57static void processList(List<Integer> numbers[1, 2, 3, 4, 5], int threshold3) {58    numbers.forEach(n -> {59        if (n > threshold) {60            System.out.println("  " + n + " exceeds " + threshold);61        }62    });63}
  3. n ->

    pass 1 of 5
    57static void processList(List<Integer> numbers, int threshold) {58    numbers.forEach(n -> {59        if (n > threshold) {
    All 5 passes — pass 1 is the card above
    passcountcounters[0]counterincgetCountfactorscaleincrement
    1
    2
    3
    4
    533⟨Counter C⟩⟨Counter lambda D⟩⟨Counter lambda E⟩5⟨EffectivelyFinal lambda F⟩⟨EffectivelyFinal lambda G⟩
  4. if (n > threshold)

    pass 1 of 2
    58numbers.forEach(n -> {59    if (n > threshold) {60        System.out.println("  " + n + " exceeds " + threshold);61    }
    output  4 exceeds 3
  5. counter ← ⟨Counter C⟩

    pass 2 of 2
    29    processList(Arrays.asList(1, 2, 3, 4, 5), 3);30    31    System.out.println("\nInstance variables:");32    33    Counter counter→ ⟨Counter C⟩ = new Counter();34    counter.demonstrate();35    36    System.out.println("\nExplicit final:");37    38    final int factor = 5;39    40    BinaryOperator<Integer> scale = (a, b) -> (a + b) * factor;41    42    System.out.println("  (2 + 3) * 5 = " + scale.apply(2, 3));43    44    System.out.println("\nArray capture:");45    46    int[] counters = {0};  // Effectively final reference, mutable content47    48    Runnable increment = () -> counters[0]++;49    50    increment.run();51    increment.run();52    increment.run();53    54    System.out.println("  Counter: " + counters[0]);55}5657static void processList(List<Integer> numbers, int threshold) {58    numbers.forEach(n -> {59        if (n > threshold) {60            System.out.println("  " + n + " exceeds " + threshold);61        }62    });63}
    output  5 exceeds 3
    
    Instance variables:
  6. inc ← ⟨Counter lambda D⟩, getCount ← ⟨Counter lambda E⟩, factor ← 5

    33        Counter counter = new Counter();34        counter.demonstrate();35        36        System.out.println("\nExplicit final:");37        38        final int factor→ 5 = 5;39        40        BinaryOperator<Integer> scale→ ⟨EffectivelyFinal lambda F⟩ = (a, b) -> (a + b) * factor;41        42        System.out.println("  (2 + 3) * 5 = " + scale.apply(2, 3));43        44        System.out.println("\nArray capture:");45        46        int[] counters = {0};  // Effectively final reference, mutable content47        48        Runnable increment→ ⟨EffectivelyFinal lambda G⟩ = () -> counters[0]++;49        50        increment.run();51        increment.run();52        increment.run();53        54        System.out.println("  Counter: " + counters[0]3);55    }56    57    static void processList(List<Integer> numbers, int threshold) {58        numbers.forEach(n -> {59            if (n > threshold) {60                System.out.println("  " + n + " exceeds " + threshold);61            }62        });63    }64}6566class Counter {67    private int count = 0;68    69    void demonstrate() {70        Runnable inc→ ⟨Counter lambda D⟩ = () -> count++;71        72        inc.run();73        inc.run();74        inc.run();75        76        System.out.println("  Count: " + count3);77        78        Supplier<Integer> getCount→ ⟨Counter lambda E⟩ = () -> this.count;79        System.out.println("  Get count: " + getCount.get());80    }
    output  Count: 3
      Get count: 3
    
    Explicit final:
      (2 + 3) * 5 = 25
    
    Array capture:
      Counter: 3

Variables accessed in lambda can't be modified. Effectively final = never reassigned.

effectively final Variable never reassigned after initialization. Required for lambda capture.

Common use cases

Where lambdas shine.

cutoff
UseCases.java
Replay: real traced execution (multi-file project)
import java.util.*;
import java.util.function.*;

public class UseCases {
    public static void main(String[] args) {
        System.out.println("Thread creation:\n");

        Thread oldThread = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("  Old way thread");
            }
        });

        Thread newThread = new Thread(() -> {
            System.out.println("  Lambda thread");
        });

        try {
            oldThread.start();
            oldThread.join();
            newThread.start();
            newThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


        System.out.println("\nSorting:");

        List<String> names = new ArrayList<>(
            Arrays.asList("Charlie", "Alice", "Bob", "David"));

        names.sort((a, b) -> a.compareTo(b));
        System.out.println("  By name: " + names);

        names.sort((a, b) -> Integer.compare(a.length(), b.length()));
        System.out.println("  By length: " + names);

        names.sort((a, b) -> {
            char lastA = a.charAt(a.length() - 1);
            char lastB = b.charAt(b.length() - 1);
            return Character.compare(lastA, lastB);
        });
        System.out.println("  By last char: " + names);

        System.out.println("\nList processing:");

        List<Integer> numbers = new ArrayList<>(
            Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));

        System.out.print("  All: ");
        numbers.forEach(n -> System.out.print(n + " "));
        System.out.println();

        numbers.removeIf(n -> n % 2 == 0);
        System.out.println("  After removing evens: " + numbers);

        numbers.replaceAll(n -> n * 10);
        System.out.println("  After * 10: " + numbers);

        System.out.println("\nMap operations:");

        Map<String, Integer> scores = new LinkedHashMap<>();
        scores.put("Alice", 85);
        scores.put("Bob", 92);
        scores.put("Charlie", 78);

        scores.forEach((name, score) ->
            System.out.println("  " + name + ": " + score));

        scores.replaceAll((name, score) -> score + 5);  // Curve grades
        System.out.println("  After curve: " + scores);

        scores.computeIfAbsent("David", k -> 80);
        System.out.println("  After adding David: " + scores);

        System.out.println("\nCustom callbacks:");

        processData(Arrays.asList(1, 2, 3, 4, 5),
            n -> n * 2,
            n -> System.out.println("  Processed: " + n)
        );

        System.out.println("\nEvent handlers:");

        Button button = new Button("Click me");

        button.setOnClick(() -> System.out.println("  Button clicked!"));
        button.setOnClick(() -> System.out.println("  Action performed"));

        button.click();

        System.out.println("\nConditional logic:");

        List<Integer> values = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

        int cutoff = 5;
        filterAndPrint(values, n -> n > cutoff, "Greater than " + cutoff);
        filterAndPrint(values, n -> n % 2 == 0, "Even numbers");
        filterAndPrint(values, n -> n % 3 == 0, "Divisible by 3");
    }

    static void processData(List<Integer> data,
                           Function<Integer, Integer> processor,
                           Consumer<Integer> outputter) {
        for (Integer item : data) {
            Integer processed = processor.apply(item);
            outputter.accept(processed);
        }
    }

    static void filterAndPrint(List<Integer> list,
                               Predicate<Integer> filter,
                               String label) {
        System.out.print("  " + label + ": ");
        list.stream()
            .filter(filter)
            .forEach(n -> System.out.print(n + " "));
        System.out.println();
    }
}

class Button {
    private String text;
    private Runnable onClick;

    Button(String text) {
        this.text = text;
    }

    void setOnClick(Runnable action) {
        this.onClick = action;
    }

    void click() {
        if (onClick != null) {
            onClick.run();
        }
    }
}
import java.util.*;
import java.util.function.*;

public class UseCases {
    public static void main(String[] args) {
        System.out.println("Thread creation:\n");

        Thread oldThread = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("  Old way thread");
            }
        });

        Thread newThread = new Thread(() -> {
            System.out.println("  Lambda thread");
        });

        try {
            oldThread.start();
            oldThread.join();
            newThread.start();
            newThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


        System.out.println("\nSorting:");

        List<String> names = new ArrayList<>(
            Arrays.asList("Charlie", "Alice", "Bob", "David"));

        names.sort((a, b) -> a.compareTo(b));
        System.out.println("  By name: " + names);

        names.sort((a, b) -> Integer.compare(a.length(), b.length()));
        System.out.println("  By length: " + names);

        names.sort((a, b) -> {
            char lastA = a.charAt(a.length() - 1);
            char lastB = b.charAt(b.length() - 1);
            return Character.compare(lastA, lastB);
        });
        System.out.println("  By last char: " + names);

        System.out.println("\nList processing:");

        List<Integer> numbers = new ArrayList<>(
            Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));

        System.out.print("  All: ");
        numbers.forEach(n -> System.out.print(n + " "));
        System.out.println();

        numbers.removeIf(n -> n % 2 == 0);
        System.out.println("  After removing evens: " + numbers);

        numbers.replaceAll(n -> n * 10);
        System.out.println("  After * 10: " + numbers);

        System.out.println("\nMap operations:");

        Map<String, Integer> scores = new LinkedHashMap<>();
        scores.put("Alice", 85);
        scores.put("Bob", 92);
        scores.put("Charlie", 78);

        scores.forEach((name, score) ->
            System.out.println("  " + name + ": " + score));

        scores.replaceAll((name, score) -> score + 5);  // Curve grades
        System.out.println("  After curve: " + scores);

        scores.computeIfAbsent("David", k -> 80);
        System.out.println("  After adding David: " + scores);

        System.out.println("\nCustom callbacks:");

        processData(Arrays.asList(1, 2, 3, 4, 5),
            n -> n * 2,
            n -> System.out.println("  Processed: " + n)
        );

        System.out.println("\nEvent handlers:");

        Button button = new Button("Click me");

        button.setOnClick(() -> System.out.println("  Button clicked!"));
        button.setOnClick(() -> System.out.println("  Action performed"));

        button.click();

        System.out.println("\nConditional logic:");

        List<Integer> values = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

        int cutoff = 3;
        filterAndPrint(values, n -> n > cutoff, "Greater than " + cutoff);
        filterAndPrint(values, n -> n % 2 == 0, "Even numbers");
        filterAndPrint(values, n -> n % 3 == 0, "Divisible by 3");
    }

    static void processData(List<Integer> data,
                           Function<Integer, Integer> processor,
                           Consumer<Integer> outputter) {
        for (Integer item : data) {
            Integer processed = processor.apply(item);
            outputter.accept(processed);
        }
    }

    static void filterAndPrint(List<Integer> list,
                               Predicate<Integer> filter,
                               String label) {
        System.out.print("  " + label + ": ");
        list.stream()
            .filter(filter)
            .forEach(n -> System.out.print(n + " "));
        System.out.println();
    }
}

class Button {
    private String text;
    private Runnable onClick;

    Button(String text) {
        this.text = text;
    }

    void setOnClick(Runnable action) {
        this.onClick = action;
    }

    void click() {
        if (onClick != null) {
            onClick.run();
        }
    }
}
import java.util.*;
import java.util.function.*;

public class UseCases {
    public static void main(String[] args) {
        System.out.println("Thread creation:\n");

        Thread oldThread = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("  Old way thread");
            }
        });

        Thread newThread = new Thread(() -> {
            System.out.println("  Lambda thread");
        });

        try {
            oldThread.start();
            oldThread.join();
            newThread.start();
            newThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


        System.out.println("\nSorting:");

        List<String> names = new ArrayList<>(
            Arrays.asList("Charlie", "Alice", "Bob", "David"));

        names.sort((a, b) -> a.compareTo(b));
        System.out.println("  By name: " + names);

        names.sort((a, b) -> Integer.compare(a.length(), b.length()));
        System.out.println("  By length: " + names);

        names.sort((a, b) -> {
            char lastA = a.charAt(a.length() - 1);
            char lastB = b.charAt(b.length() - 1);
            return Character.compare(lastA, lastB);
        });
        System.out.println("  By last char: " + names);

        System.out.println("\nList processing:");

        List<Integer> numbers = new ArrayList<>(
            Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));

        System.out.print("  All: ");
        numbers.forEach(n -> System.out.print(n + " "));
        System.out.println();

        numbers.removeIf(n -> n % 2 == 0);
        System.out.println("  After removing evens: " + numbers);

        numbers.replaceAll(n -> n * 10);
        System.out.println("  After * 10: " + numbers);

        System.out.println("\nMap operations:");

        Map<String, Integer> scores = new LinkedHashMap<>();
        scores.put("Alice", 85);
        scores.put("Bob", 92);
        scores.put("Charlie", 78);

        scores.forEach((name, score) ->
            System.out.println("  " + name + ": " + score));

        scores.replaceAll((name, score) -> score + 5);  // Curve grades
        System.out.println("  After curve: " + scores);

        scores.computeIfAbsent("David", k -> 80);
        System.out.println("  After adding David: " + scores);

        System.out.println("\nCustom callbacks:");

        processData(Arrays.asList(1, 2, 3, 4, 5),
            n -> n * 2,
            n -> System.out.println("  Processed: " + n)
        );

        System.out.println("\nEvent handlers:");

        Button button = new Button("Click me");

        button.setOnClick(() -> System.out.println("  Button clicked!"));
        button.setOnClick(() -> System.out.println("  Action performed"));

        button.click();

        System.out.println("\nConditional logic:");

        List<Integer> values = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

        int cutoff = 8;
        filterAndPrint(values, n -> n > cutoff, "Greater than " + cutoff);
        filterAndPrint(values, n -> n % 2 == 0, "Even numbers");
        filterAndPrint(values, n -> n % 3 == 0, "Divisible by 3");
    }

    static void processData(List<Integer> data,
                           Function<Integer, Integer> processor,
                           Consumer<Integer> outputter) {
        for (Integer item : data) {
            Integer processed = processor.apply(item);
            outputter.accept(processed);
        }
    }

    static void filterAndPrint(List<Integer> list,
                               Predicate<Integer> filter,
                               String label) {
        System.out.print("  " + label + ": ");
        list.stream()
            .filter(filter)
            .forEach(n -> System.out.print(n + " "));
        System.out.println();
    }
}

class Button {
    private String text;
    private Runnable onClick;

    Button(String text) {
        this.text = text;
    }

    void setOnClick(Runnable action) {
        this.onClick = action;
    }

    void click() {
        if (onClick != null) {
            onClick.run();
        }
    }
}
  1. oldThread ← Thread[#19,Thread-0,5,main], newThread ← Thread[#20,Thread-1,5,main]

    4public class UseCases {5    public static void main(String[] args) {6        System.out.println("Thread creation:\n");7        8        Thread oldThread→ Thread[#19,Thread-0,5,main] = new Thread(new Runnable() {9            @Override10            public void run() {11                System.out.println("  Old way thread");12            }13        });14        15        Thread newThread→ Thread[#20,Thread-1,5,main] = new Thread(() -> {16            System.out.println("  Lambda thread");17        });
    outputThread creation:
  2. oldThread.join();

    10    public void run() {11        System.out.println("  Old way thread");12    }13});1415Thread newThread = new Thread(() -> {16    System.out.println("  Lambda thread");17});1819try {20    oldThread.start();21    oldThread.join();22    newThread.start();23    newThread.join();24} catch (InterruptedException e) {
    output  Old way thread
  3. () ->

    15Thread newThread = new Thread(() -> {16    System.out.println("  Lambda thread");17});
    output  Lambda thread
  4. newThread.join();

    22    newThread.start();23    newThread.join();24} catch (InterruptedException e) {
  5. names ← [Charlie, Alice, Bob, David], numbers ← [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

    29System.out.println("\nSorting:");3031List<String> names→ [Charlie, Alice, Bob, David] = new ArrayList<>(32    Arrays.asList("Charlie", "Alice", "Bob", "David"));3334names.sort((a, b) -> a.compareTo(b));35System.out.println("  By name: " + names[Alice, Bob, Charlie, David]);3637names.sort((a, b) -> Integer.compare(a.length(), b.length()));38System.out.println("  By length: " + names[Bob, Alice, David, Charlie]);3940names.sort((a, b) -> {41    char lastA = a.charAt(a.length() - 1);42    char lastB = b.charAt(b.length() - 1);43    return Character.compare(lastA, lastB);44});45System.out.println("  By last char: " + names[Bob, David, Alice, Charlie]);4647System.out.println("\nList processing:");4849List<Integer> numbers→ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] = new ArrayList<>(50    Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));5152System.out.print("  All: ");53numbers.forEach(n -> System.out.print(n + " "));54System.out.println();5556numbers.removeIf(n -> n % 2 == 0);57System.out.println("  After removing evens: " + numbers[1, 3, 5, 7, 9]);5859numbers.replaceAll(n -> n * 10);60System.out.println("  After * 10: " + numbers[10, 30, 50, 70, 90]);6162System.out.println("\nMap operations:");6364Map<String, Integer> scores→ {} = new LinkedHashMap<>();65scores.put("Alice", 85);66scores.put("Bob", 92);67scores.put("Charlie", 78);6869scores.forEach((name, score) -> 70    System.out.println("  " + name + ": " + score));7172scores.replaceAll((name, score) -> score + 5);  // Curve grades73System.out.println("  After curve: " + scores{Alice=90, Bob=97, Charlie=83});7475scores.computeIfAbsent("David", k -> 80);76System.out.println("  After adding David: " + scores{Alice=90, Bob=97, Charlie=83, David=80});7778System.out.println("\nCustom callbacks:");7980processData(Arrays.asList(1, 2, 3, 4, 5),81    n -> n * 2,82    n -> System.out.println("  Processed: " + n)83);
    output
    Sorting:
      By name: [Alice, Bob, Charlie, David]
      By length: [Bob, Alice, David, Charlie]
      By last char: [Bob, David, Alice, Charlie]
    
    List processing:
      All:
      After removing evens: [1, 3, 5, 7, 9]
      After * 10: [10, 30, 50, 70, 90]
    
    Map operations:
      After curve: {Alice=90, Bob=97, Charlie=83}
      After adding David: {Alice=90, Bob=97, Charlie=83, David=80}
    
    Custom callbacks:
  6. static void processData(List<Integer> data, …

    104static void processData(List<Integer> data[1, 2, 3, 4, 5],105                       Function<Integer, Integer> processor⟨UseCases lambda A⟩,106                       Consumer<Integer> outputter⟨UseCases lambda B⟩) {107    for (Integer item : data) {
  7. processed ← 2

    pass 1 of 5
    106                   Consumer<Integer> outputter) {107for (Integer item1 : data[1, 2, 3, 4, 5]) {108    Integer processed→ 2 = processor.apply(item1);109    outputter.accept(processed2);110}
    All 5 passes — pass 1 is the card above
    passitemtextactiononClickprocessedthis.textbuttonthis.onClickvaluescutoff
    112
    224
    336
    448
    55Click me⟨UseCases lambda C⟩⟨UseCases lambda D⟩10Click me⟨Button E⟩⟨UseCases lambda C⟩[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]5
  8. this.text ← Click me, button ← ⟨Button E⟩

    87        Button button→ ⟨Button E⟩ = new Button("Click me");88        89        button.setOnClick(() -> System.out.println("  Button clicked!"));90        button.setOnClick(() -> System.out.println("  Action performed"));91        92        button.click();93        94        System.out.println("\nConditional logic:");95        96        List<Integer> values = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);97        98        int cutoff = 5; //@cutoff=5, 3, 899        filterAndPrint(values, n -> n > cutoff, "Greater than " + cutoff);100        filterAndPrint(values, n -> n % 2 == 0, "Even numbers");101        filterAndPrint(values, n -> n % 3 == 0, "Divisible by 3");102    }103    104    static void processData(List<Integer> data,105                           Function<Integer, Integer> processor,106                           Consumer<Integer> outputter) {107        for (Integer item : data) {108            Integer processed = processor.apply(item);109            outputter.accept(processed);110        }111    }112    113    static void filterAndPrint(List<Integer> list, 114                               Predicate<Integer> filter,115                               String label) {116        System.out.print("  " + label + ": ");117        list.stream()118            .filter(filter)119            .forEach(n -> System.out.print(n + " "));120        System.out.println();121    }122}123124class Button {125    private String text;126    private Runnable onClick;127    128    Button(String textClick me) {129        this.text→ Click me = textClick me;130    }
  9. this.onClick ← ⟨UseCases lambda C⟩

    pass 1 of 2
    89        button.setOnClick(() -> System.out.println("  Button clicked!"));90        button.setOnClick(() -> System.out.println("  Action performed"));91        92        button.click();93        94        System.out.println("\nConditional logic:");95        96        List<Integer> values = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);97        98        int cutoff = 5; //@cutoff=5, 3, 899        filterAndPrint(values, n -> n > cutoff, "Greater than " + cutoff);100        filterAndPrint(values, n -> n % 2 == 0, "Even numbers");101        filterAndPrint(values, n -> n % 3 == 0, "Divisible by 3");102    }103    104    static void processData(List<Integer> data,105                           Function<Integer, Integer> processor,106                           Consumer<Integer> outputter) {107        for (Integer item : data) {108            Integer processed = processor.apply(item);109            outputter.accept(processed);110        }111    }112    113    static void filterAndPrint(List<Integer> list, 114                               Predicate<Integer> filter,115                               String label) {116        System.out.print("  " + label + ": ");117        list.stream()118            .filter(filter)119            .forEach(n -> System.out.print(n + " "));120        System.out.println();121    }122}123124class Button {125    private String text;126    private Runnable onClick;127    128    Button(String text) {129        this.text = text;130    }131    132    void setOnClick(Runnable action⟨UseCases lambda C⟩) {133        this.onClick→ ⟨UseCases lambda C⟩ = action⟨UseCases lambda C⟩;134    }
  10. this.onClick ← ⟨UseCases lambda D⟩

    pass 2 of 2
    89        button.setOnClick(() -> System.out.println("  Button clicked!"));90        button.setOnClick(() -> System.out.println("  Action performed"));91        92        button.click();93        94        System.out.println("\nConditional logic:");95        96        List<Integer> values = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);97        98        int cutoff = 5; //@cutoff=5, 3, 899        filterAndPrint(values, n -> n > cutoff, "Greater than " + cutoff);100        filterAndPrint(values, n -> n % 2 == 0, "Even numbers");101        filterAndPrint(values, n -> n % 3 == 0, "Divisible by 3");102    }103    104    static void processData(List<Integer> data,105                           Function<Integer, Integer> processor,106                           Consumer<Integer> outputter) {107        for (Integer item : data) {108            Integer processed = processor.apply(item);109            outputter.accept(processed);110        }111    }112    113    static void filterAndPrint(List<Integer> list, 114                               Predicate<Integer> filter,115                               String label) {116        System.out.print("  " + label + ": ");117        list.stream()118            .filter(filter)119            .forEach(n -> System.out.print(n + " "));120        System.out.println();121    }122}123124class Button {125    private String text;126    private Runnable onClick;127    128    Button(String text) {129        this.text = text;130    }131    132    void setOnClick(Runnable action⟨UseCases lambda D⟩) {133        this.onClick→ ⟨UseCases lambda D⟩ = action⟨UseCases lambda D⟩;134    }
  11. values ← [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], cutoff ← 5

    92        button.click();93        94        System.out.println("\nConditional logic:");95        96        List<Integer> values→ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);97        98        int cutoff→ 5 = 5; //@cutoff=5, 3, 899        filterAndPrint(values[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], n -> n > cutoff, "Greater than " + cutoff5);100        filterAndPrint(values, n -> n % 2 == 0, "Even numbers");101        filterAndPrint(values, n -> n % 3 == 0, "Divisible by 3");102    }103    104    static void processData(List<Integer> data,105                           Function<Integer, Integer> processor,106                           Consumer<Integer> outputter) {107        for (Integer item : data) {108            Integer processed = processor.apply(item);109            outputter.accept(processed);110        }111    }112    113    static void filterAndPrint(List<Integer> list, 114                               Predicate<Integer> filter,115                               String label) {116        System.out.print("  " + label + ": ");117        list.stream()118            .filter(filter)119            .forEach(n -> System.out.print(n + " "));120        System.out.println();121    }122}123124class Button {125    private String text;126    private Runnable onClick;127    128    Button(String text) {129        this.text = text;130    }131    132    void setOnClick(Runnable action) {133        this.onClick = action;134    }135    136    void click() {137        if (onClick⟨UseCases lambda D⟩ != null) {138            onClick.run();139        }
    output
    Conditional logic:
  12. static void filterAndPrint(List<Integer> list, …

    pass 1 of 3
    98    int cutoff = 5; //@cutoff=5, 3, 899    filterAndPrint(values[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], n -> n > cutoff, "Greater than " + cutoff5);100    filterAndPrint(values[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], n -> n % 2 == 0, "Even numbers");101    filterAndPrint(values, n -> n % 3 == 0, "Divisible by 3");102}103104static void processData(List<Integer> data,105                       Function<Integer, Integer> processor,106                       Consumer<Integer> outputter) {107    for (Integer item : data) {108        Integer processed = processor.apply(item);109        outputter.accept(processed);110    }111}112113static void filterAndPrint(List<Integer> list[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 114                           Predicate<Integer> filter⟨UseCases lambda F⟩,115                           String labelGreater than 5) {116    System.out.print("  " + labelGreater than 5 + ": ");117    list.stream()118        .filter(filter⟨UseCases lambda F⟩)119        .forEach(n -> System.out.print(n + " "));120    System.out.println();121}
    output  Greater than 5: 
    All 3 passes — pass 1 is the card above
    passfilterlabelcutoff
    1⟨UseCases lambda F⟩Greater than 55
    2⟨UseCases lambda G⟩Even numbers
    3⟨UseCases lambda H⟩Divisible by 3
  1. oldThread ← Thread[#19,Thread-0,5,main], newThread ← Thread[#20,Thread-1,5,main]

    4public class UseCases {5    public static void main(String[] args) {6        System.out.println("Thread creation:\n");7        8        Thread oldThread→ Thread[#19,Thread-0,5,main] = new Thread(new Runnable() {9            @Override10            public void run() {11                System.out.println("  Old way thread");12            }13        });14        15        Thread newThread→ Thread[#20,Thread-1,5,main] = new Thread(() -> {16            System.out.println("  Lambda thread");17        });
    outputThread creation:
  2. @Override public void run()

    8Thread oldThread = new Thread(new Runnable() {9    @Override10    public void run() {11        System.out.println("  Old way thread");12    }
    output  Old way thread
  3. oldThread.join();

    20oldThread.start();21oldThread.join();22newThread.start();23newThread.join();
  4. newThread.join();

    15Thread newThread = new Thread(() -> {16    System.out.println("  Lambda thread");17});1819try {20    oldThread.start();21    oldThread.join();22    newThread.start();23    newThread.join();24} catch (InterruptedException e) {
    output  Lambda thread
  5. names ← [Charlie, Alice, Bob, David], numbers ← [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

    29System.out.println("\nSorting:");3031List<String> names→ [Charlie, Alice, Bob, David] = new ArrayList<>(32    Arrays.asList("Charlie", "Alice", "Bob", "David"));3334names.sort((a, b) -> a.compareTo(b));35System.out.println("  By name: " + names[Alice, Bob, Charlie, David]);3637names.sort((a, b) -> Integer.compare(a.length(), b.length()));38System.out.println("  By length: " + names[Bob, Alice, David, Charlie]);3940names.sort((a, b) -> {41    char lastA = a.charAt(a.length() - 1);42    char lastB = b.charAt(b.length() - 1);43    return Character.compare(lastA, lastB);44});45System.out.println("  By last char: " + names[Bob, David, Alice, Charlie]);4647System.out.println("\nList processing:");4849List<Integer> numbers→ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] = new ArrayList<>(50    Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));5152System.out.print("  All: ");53numbers.forEach(n -> System.out.print(n + " "));54System.out.println();5556numbers.removeIf(n -> n % 2 == 0);57System.out.println("  After removing evens: " + numbers[1, 3, 5, 7, 9]);5859numbers.replaceAll(n -> n * 10);60System.out.println("  After * 10: " + numbers[10, 30, 50, 70, 90]);6162System.out.println("\nMap operations:");6364Map<String, Integer> scores→ {} = new LinkedHashMap<>();65scores.put("Alice", 85);66scores.put("Bob", 92);67scores.put("Charlie", 78);6869scores.forEach((name, score) -> 70    System.out.println("  " + name + ": " + score));7172scores.replaceAll((name, score) -> score + 5);  // Curve grades73System.out.println("  After curve: " + scores{Alice=90, Bob=97, Charlie=83});7475scores.computeIfAbsent("David", k -> 80);76System.out.println("  After adding David: " + scores{Alice=90, Bob=97, Charlie=83, David=80});7778System.out.println("\nCustom callbacks:");7980processData(Arrays.asList(1, 2, 3, 4, 5),81    n -> n * 2,82    n -> System.out.println("  Processed: " + n)83);
    output
    Sorting:
      By name: [Alice, Bob, Charlie, David]
      By length: [Bob, Alice, David, Charlie]
      By last char: [Bob, David, Alice, Charlie]
    
    List processing:
      All:
      After removing evens: [1, 3, 5, 7, 9]
      After * 10: [10, 30, 50, 70, 90]
    
    Map operations:
      After curve: {Alice=90, Bob=97, Charlie=83}
      After adding David: {Alice=90, Bob=97, Charlie=83, David=80}
    
    Custom callbacks:
  6. static void processData(List<Integer> data, …

    104static void processData(List<Integer> data[1, 2, 3, 4, 5],105                       Function<Integer, Integer> processor⟨UseCases lambda A⟩,106                       Consumer<Integer> outputter⟨UseCases lambda B⟩) {107    for (Integer item : data) {
  7. processed ← 2

    pass 1 of 5
    106                   Consumer<Integer> outputter) {107for (Integer item1 : data[1, 2, 3, 4, 5]) {108    Integer processed→ 2 = processor.apply(item1);109    outputter.accept(processed2);110}
    All 5 passes — pass 1 is the card above
    passitemtextactiononClickprocessedthis.textbuttonthis.onClickvaluescutoff
    112
    224
    336
    448
    55Click me⟨UseCases lambda C⟩⟨UseCases lambda D⟩10Click me⟨Button E⟩⟨UseCases lambda C⟩[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]3
  8. this.text ← Click me, button ← ⟨Button E⟩

    87        Button button→ ⟨Button E⟩ = new Button("Click me");88        89        button.setOnClick(() -> System.out.println("  Button clicked!"));90        button.setOnClick(() -> System.out.println("  Action performed"));91        92        button.click();93        94        System.out.println("\nConditional logic:");95        96        List<Integer> values = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);97        98        int cutoff = 3;99        filterAndPrint(values, n -> n > cutoff, "Greater than " + cutoff);100        filterAndPrint(values, n -> n % 2 == 0, "Even numbers");101        filterAndPrint(values, n -> n % 3 == 0, "Divisible by 3");102    }103    104    static void processData(List<Integer> data,105                           Function<Integer, Integer> processor,106                           Consumer<Integer> outputter) {107        for (Integer item : data) {108            Integer processed = processor.apply(item);109            outputter.accept(processed);110        }111    }112    113    static void filterAndPrint(List<Integer> list, 114                               Predicate<Integer> filter,115                               String label) {116        System.out.print("  " + label + ": ");117        list.stream()118            .filter(filter)119            .forEach(n -> System.out.print(n + " "));120        System.out.println();121    }122}123124class Button {125    private String text;126    private Runnable onClick;127    128    Button(String textClick me) {129        this.text→ Click me = textClick me;130    }
  9. this.onClick ← ⟨UseCases lambda C⟩

    pass 1 of 2
    89        button.setOnClick(() -> System.out.println("  Button clicked!"));90        button.setOnClick(() -> System.out.println("  Action performed"));91        92        button.click();93        94        System.out.println("\nConditional logic:");95        96        List<Integer> values = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);97        98        int cutoff = 3;99        filterAndPrint(values, n -> n > cutoff, "Greater than " + cutoff);100        filterAndPrint(values, n -> n % 2 == 0, "Even numbers");101        filterAndPrint(values, n -> n % 3 == 0, "Divisible by 3");102    }103    104    static void processData(List<Integer> data,105                           Function<Integer, Integer> processor,106                           Consumer<Integer> outputter) {107        for (Integer item : data) {108            Integer processed = processor.apply(item);109            outputter.accept(processed);110        }111    }112    113    static void filterAndPrint(List<Integer> list, 114                               Predicate<Integer> filter,115                               String label) {116        System.out.print("  " + label + ": ");117        list.stream()118            .filter(filter)119            .forEach(n -> System.out.print(n + " "));120        System.out.println();121    }122}123124class Button {125    private String text;126    private Runnable onClick;127    128    Button(String text) {129        this.text = text;130    }131    132    void setOnClick(Runnable action⟨UseCases lambda C⟩) {133        this.onClick→ ⟨UseCases lambda C⟩ = action⟨UseCases lambda C⟩;134    }
  10. this.onClick ← ⟨UseCases lambda D⟩

    pass 2 of 2
    89        button.setOnClick(() -> System.out.println("  Button clicked!"));90        button.setOnClick(() -> System.out.println("  Action performed"));91        92        button.click();93        94        System.out.println("\nConditional logic:");95        96        List<Integer> values = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);97        98        int cutoff = 3;99        filterAndPrint(values, n -> n > cutoff, "Greater than " + cutoff);100        filterAndPrint(values, n -> n % 2 == 0, "Even numbers");101        filterAndPrint(values, n -> n % 3 == 0, "Divisible by 3");102    }103    104    static void processData(List<Integer> data,105                           Function<Integer, Integer> processor,106                           Consumer<Integer> outputter) {107        for (Integer item : data) {108            Integer processed = processor.apply(item);109            outputter.accept(processed);110        }111    }112    113    static void filterAndPrint(List<Integer> list, 114                               Predicate<Integer> filter,115                               String label) {116        System.out.print("  " + label + ": ");117        list.stream()118            .filter(filter)119            .forEach(n -> System.out.print(n + " "));120        System.out.println();121    }122}123124class Button {125    private String text;126    private Runnable onClick;127    128    Button(String text) {129        this.text = text;130    }131    132    void setOnClick(Runnable action⟨UseCases lambda D⟩) {133        this.onClick→ ⟨UseCases lambda D⟩ = action⟨UseCases lambda D⟩;134    }
  11. values ← [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], cutoff ← 3

    92        button.click();93        94        System.out.println("\nConditional logic:");95        96        List<Integer> values→ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);97        98        int cutoff→ 3 = 3;99        filterAndPrint(values[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], n -> n > cutoff, "Greater than " + cutoff3);100        filterAndPrint(values, n -> n % 2 == 0, "Even numbers");101        filterAndPrint(values, n -> n % 3 == 0, "Divisible by 3");102    }103    104    static void processData(List<Integer> data,105                           Function<Integer, Integer> processor,106                           Consumer<Integer> outputter) {107        for (Integer item : data) {108            Integer processed = processor.apply(item);109            outputter.accept(processed);110        }111    }112    113    static void filterAndPrint(List<Integer> list, 114                               Predicate<Integer> filter,115                               String label) {116        System.out.print("  " + label + ": ");117        list.stream()118            .filter(filter)119            .forEach(n -> System.out.print(n + " "));120        System.out.println();121    }122}123124class Button {125    private String text;126    private Runnable onClick;127    128    Button(String text) {129        this.text = text;130    }131    132    void setOnClick(Runnable action) {133        this.onClick = action;134    }135    136    void click() {137        if (onClick⟨UseCases lambda D⟩ != null) {138            onClick.run();139        }
    output
    Conditional logic:
  12. static void filterAndPrint(List<Integer> list, …

    pass 1 of 3
    98    int cutoff = 3;99    filterAndPrint(values[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], n -> n > cutoff, "Greater than " + cutoff3);100    filterAndPrint(values[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], n -> n % 2 == 0, "Even numbers");101    filterAndPrint(values, n -> n % 3 == 0, "Divisible by 3");102}103104static void processData(List<Integer> data,105                       Function<Integer, Integer> processor,106                       Consumer<Integer> outputter) {107    for (Integer item : data) {108        Integer processed = processor.apply(item);109        outputter.accept(processed);110    }111}112113static void filterAndPrint(List<Integer> list[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 114                           Predicate<Integer> filter⟨UseCases lambda F⟩,115                           String labelGreater than 3) {116    System.out.print("  " + labelGreater than 3 + ": ");117    list.stream()118        .filter(filter⟨UseCases lambda F⟩)119        .forEach(n -> System.out.print(n + " "));120    System.out.println();121}
    output  Greater than 3: 
    All 3 passes — pass 1 is the card above
    passfilterlabelcutoff
    1⟨UseCases lambda F⟩Greater than 33
    2⟨UseCases lambda G⟩Even numbers
    3⟨UseCases lambda H⟩Divisible by 3
  1. oldThread ← Thread[#19,Thread-0,5,main], newThread ← Thread[#20,Thread-1,5,main]

    4public class UseCases {5    public static void main(String[] args) {6        System.out.println("Thread creation:\n");7        8        Thread oldThread→ Thread[#19,Thread-0,5,main] = new Thread(new Runnable() {9            @Override10            public void run() {11                System.out.println("  Old way thread");12            }13        });14        15        Thread newThread→ Thread[#20,Thread-1,5,main] = new Thread(() -> {16            System.out.println("  Lambda thread");17        });
    outputThread creation:
  2. @Override public void run()

    8Thread oldThread = new Thread(new Runnable() {9    @Override10    public void run() {11        System.out.println("  Old way thread");12    }
    output  Old way thread
  3. oldThread.join();

    20    oldThread.start();21    oldThread.join();22    newThread.start();23    newThread.join();24} catch (InterruptedException e) {
  4. () ->

    15Thread newThread = new Thread(() -> {16    System.out.println("  Lambda thread");17});
    output  Lambda thread
  5. newThread.join();

    22    newThread.start();23    newThread.join();24} catch (InterruptedException e) {
  6. names ← [Charlie, Alice, Bob, David], numbers ← [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

    29System.out.println("\nSorting:");3031List<String> names→ [Charlie, Alice, Bob, David] = new ArrayList<>(32    Arrays.asList("Charlie", "Alice", "Bob", "David"));3334names.sort((a, b) -> a.compareTo(b));35System.out.println("  By name: " + names[Alice, Bob, Charlie, David]);3637names.sort((a, b) -> Integer.compare(a.length(), b.length()));38System.out.println("  By length: " + names[Bob, Alice, David, Charlie]);3940names.sort((a, b) -> {41    char lastA = a.charAt(a.length() - 1);42    char lastB = b.charAt(b.length() - 1);43    return Character.compare(lastA, lastB);44});45System.out.println("  By last char: " + names[Bob, David, Alice, Charlie]);4647System.out.println("\nList processing:");4849List<Integer> numbers→ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] = new ArrayList<>(50    Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));5152System.out.print("  All: ");53numbers.forEach(n -> System.out.print(n + " "));54System.out.println();5556numbers.removeIf(n -> n % 2 == 0);57System.out.println("  After removing evens: " + numbers[1, 3, 5, 7, 9]);5859numbers.replaceAll(n -> n * 10);60System.out.println("  After * 10: " + numbers[10, 30, 50, 70, 90]);6162System.out.println("\nMap operations:");6364Map<String, Integer> scores→ {} = new LinkedHashMap<>();65scores.put("Alice", 85);66scores.put("Bob", 92);67scores.put("Charlie", 78);6869scores.forEach((name, score) -> 70    System.out.println("  " + name + ": " + score));7172scores.replaceAll((name, score) -> score + 5);  // Curve grades73System.out.println("  After curve: " + scores{Alice=90, Bob=97, Charlie=83});7475scores.computeIfAbsent("David", k -> 80);76System.out.println("  After adding David: " + scores{Alice=90, Bob=97, Charlie=83, David=80});7778System.out.println("\nCustom callbacks:");7980processData(Arrays.asList(1, 2, 3, 4, 5),81    n -> n * 2,82    n -> System.out.println("  Processed: " + n)83);
    output
    Sorting:
      By name: [Alice, Bob, Charlie, David]
      By length: [Bob, Alice, David, Charlie]
      By last char: [Bob, David, Alice, Charlie]
    
    List processing:
      All:
      After removing evens: [1, 3, 5, 7, 9]
      After * 10: [10, 30, 50, 70, 90]
    
    Map operations:
      After curve: {Alice=90, Bob=97, Charlie=83}
      After adding David: {Alice=90, Bob=97, Charlie=83, David=80}
    
    Custom callbacks:
  7. static void processData(List<Integer> data, …

    104static void processData(List<Integer> data[1, 2, 3, 4, 5],105                       Function<Integer, Integer> processor⟨UseCases lambda A⟩,106                       Consumer<Integer> outputter⟨UseCases lambda B⟩) {107    for (Integer item : data) {
  8. processed ← 2

    pass 1 of 5
    106                   Consumer<Integer> outputter) {107for (Integer item1 : data[1, 2, 3, 4, 5]) {108    Integer processed→ 2 = processor.apply(item1);109    outputter.accept(processed2);110}
    All 5 passes — pass 1 is the card above
    passitemtextactiononClickprocessedthis.textbuttonthis.onClickvaluescutoff
    112
    224
    336
    448
    55Click me⟨UseCases lambda C⟩⟨UseCases lambda D⟩10Click me⟨Button E⟩⟨UseCases lambda C⟩[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]8
  9. this.text ← Click me, button ← ⟨Button E⟩

    87        Button button→ ⟨Button E⟩ = new Button("Click me");88        89        button.setOnClick(() -> System.out.println("  Button clicked!"));90        button.setOnClick(() -> System.out.println("  Action performed"));91        92        button.click();93        94        System.out.println("\nConditional logic:");95        96        List<Integer> values = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);97        98        int cutoff = 8;99        filterAndPrint(values, n -> n > cutoff, "Greater than " + cutoff);100        filterAndPrint(values, n -> n % 2 == 0, "Even numbers");101        filterAndPrint(values, n -> n % 3 == 0, "Divisible by 3");102    }103    104    static void processData(List<Integer> data,105                           Function<Integer, Integer> processor,106                           Consumer<Integer> outputter) {107        for (Integer item : data) {108            Integer processed = processor.apply(item);109            outputter.accept(processed);110        }111    }112    113    static void filterAndPrint(List<Integer> list, 114                               Predicate<Integer> filter,115                               String label) {116        System.out.print("  " + label + ": ");117        list.stream()118            .filter(filter)119            .forEach(n -> System.out.print(n + " "));120        System.out.println();121    }122}123124class Button {125    private String text;126    private Runnable onClick;127    128    Button(String textClick me) {129        this.text→ Click me = textClick me;130    }
  10. this.onClick ← ⟨UseCases lambda C⟩

    pass 1 of 2
    89        button.setOnClick(() -> System.out.println("  Button clicked!"));90        button.setOnClick(() -> System.out.println("  Action performed"));91        92        button.click();93        94        System.out.println("\nConditional logic:");95        96        List<Integer> values = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);97        98        int cutoff = 8;99        filterAndPrint(values, n -> n > cutoff, "Greater than " + cutoff);100        filterAndPrint(values, n -> n % 2 == 0, "Even numbers");101        filterAndPrint(values, n -> n % 3 == 0, "Divisible by 3");102    }103    104    static void processData(List<Integer> data,105                           Function<Integer, Integer> processor,106                           Consumer<Integer> outputter) {107        for (Integer item : data) {108            Integer processed = processor.apply(item);109            outputter.accept(processed);110        }111    }112    113    static void filterAndPrint(List<Integer> list, 114                               Predicate<Integer> filter,115                               String label) {116        System.out.print("  " + label + ": ");117        list.stream()118            .filter(filter)119            .forEach(n -> System.out.print(n + " "));120        System.out.println();121    }122}123124class Button {125    private String text;126    private Runnable onClick;127    128    Button(String text) {129        this.text = text;130    }131    132    void setOnClick(Runnable action⟨UseCases lambda C⟩) {133        this.onClick→ ⟨UseCases lambda C⟩ = action⟨UseCases lambda C⟩;134    }
  11. this.onClick ← ⟨UseCases lambda D⟩

    pass 2 of 2
    89        button.setOnClick(() -> System.out.println("  Button clicked!"));90        button.setOnClick(() -> System.out.println("  Action performed"));91        92        button.click();93        94        System.out.println("\nConditional logic:");95        96        List<Integer> values = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);97        98        int cutoff = 8;99        filterAndPrint(values, n -> n > cutoff, "Greater than " + cutoff);100        filterAndPrint(values, n -> n % 2 == 0, "Even numbers");101        filterAndPrint(values, n -> n % 3 == 0, "Divisible by 3");102    }103    104    static void processData(List<Integer> data,105                           Function<Integer, Integer> processor,106                           Consumer<Integer> outputter) {107        for (Integer item : data) {108            Integer processed = processor.apply(item);109            outputter.accept(processed);110        }111    }112    113    static void filterAndPrint(List<Integer> list, 114                               Predicate<Integer> filter,115                               String label) {116        System.out.print("  " + label + ": ");117        list.stream()118            .filter(filter)119            .forEach(n -> System.out.print(n + " "));120        System.out.println();121    }122}123124class Button {125    private String text;126    private Runnable onClick;127    128    Button(String text) {129        this.text = text;130    }131    132    void setOnClick(Runnable action⟨UseCases lambda D⟩) {133        this.onClick→ ⟨UseCases lambda D⟩ = action⟨UseCases lambda D⟩;134    }
  12. values ← [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], cutoff ← 8

    92        button.click();93        94        System.out.println("\nConditional logic:");95        96        List<Integer> values→ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);97        98        int cutoff→ 8 = 8;99        filterAndPrint(values[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], n -> n > cutoff, "Greater than " + cutoff8);100        filterAndPrint(values, n -> n % 2 == 0, "Even numbers");101        filterAndPrint(values, n -> n % 3 == 0, "Divisible by 3");102    }103    104    static void processData(List<Integer> data,105                           Function<Integer, Integer> processor,106                           Consumer<Integer> outputter) {107        for (Integer item : data) {108            Integer processed = processor.apply(item);109            outputter.accept(processed);110        }111    }112    113    static void filterAndPrint(List<Integer> list, 114                               Predicate<Integer> filter,115                               String label) {116        System.out.print("  " + label + ": ");117        list.stream()118            .filter(filter)119            .forEach(n -> System.out.print(n + " "));120        System.out.println();121    }122}123124class Button {125    private String text;126    private Runnable onClick;127    128    Button(String text) {129        this.text = text;130    }131    132    void setOnClick(Runnable action) {133        this.onClick = action;134    }135    136    void click() {137        if (onClick⟨UseCases lambda D⟩ != null) {138            onClick.run();139        }
    output
    Conditional logic:
  13. static void filterAndPrint(List<Integer> list, …

    pass 1 of 3
    98    int cutoff = 8;99    filterAndPrint(values[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], n -> n > cutoff, "Greater than " + cutoff8);100    filterAndPrint(values[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], n -> n % 2 == 0, "Even numbers");101    filterAndPrint(values, n -> n % 3 == 0, "Divisible by 3");102}103104static void processData(List<Integer> data,105                       Function<Integer, Integer> processor,106                       Consumer<Integer> outputter) {107    for (Integer item : data) {108        Integer processed = processor.apply(item);109        outputter.accept(processed);110    }111}112113static void filterAndPrint(List<Integer> list[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 114                           Predicate<Integer> filter⟨UseCases lambda F⟩,115                           String labelGreater than 8) {116    System.out.print("  " + labelGreater than 8 + ": ");117    list.stream()118        .filter(filter⟨UseCases lambda F⟩)119        .forEach(n -> System.out.print(n + " "));120    System.out.println();121}
    output  Greater than 8: 
    All 3 passes — pass 1 is the card above
    passfilterlabelcutoff
    1⟨UseCases lambda F⟩Greater than 88
    2⟨UseCases lambda G⟩Even numbers
    3⟨UseCases lambda H⟩Divisible by 3

Collections, streams, event handlers, callbacks - anywhere functional interfaces are used.

Exercise: Practical.java

Refactor anonymous classes to lambdas