Lambda Syntax

Forms of a Lambda

FormExampleWhen
No parameters() -> System.out.println("Hi")Runnable, Supplier
One parameter (no parentheses)x -> x * 2Function, Predicate, Consumer
Several parameters(a, b) -> a + bBiFunction, Comparator
Typed parameters(int a, int b) -> a + bwhen type inference needs help
var parameters (Java 11)(var a, var b) -> a + bto add annotations like @NonNull var a
Block bodyx -> { int y = x * 2; return y + 1; }more than one statement

All Forms in One Program

Example

Expression bodies return their value automatically. Block bodies need an explicit return.

import java.util.function.*;

public class Main {
    public static void main(String[] args) {
        Runnable hello = () -> System.out.println("Hello from a Runnable");
        Function<Integer, Integer> doubleIt = x -> x * 2;
        BinaryOperator<Integer> add = (a, b) -> a + b;
        BiFunction<Integer, Integer, Integer> power = (Integer base, Integer exp) -> {
            int result = 1;
            for (int i = 0; i < exp; i++) result *= base;
            return result;
        };

        hello.run();
        System.out.println("doubleIt(21) = " + doubleIt.apply(21));
        System.out.println("add(10, 5)   = " + add.apply(10, 5));
        System.out.println("power(2, 10) = " + power.apply(2, 10));
    }
}

Output

Hello from a Runnable
doubleIt(21) = 42
add(10, 5)   = 15
power(2, 10) = 1024

Practice

Exercise: Write a lambda of type BiFunction<String, Integer, String> that repeats a string n times, and print repeat.apply("ab", 3).

Show answer
BiFunction<String, Integer, String> repeat = (s, n) -> s.repeat(n);
System.out.println(repeat.apply("ab", 3)); // ababab