CodeBlanks Logo Icon CodeBlanks

Parameterized lambda

Learn parameterized lambdas with (x) -> ....

Parameterized lambda

A lambda can take parameters: (String s) -> s.length(). The type is usually inferred; (s) -> s.length() also works. With a single parameter the parentheses are optional: s -> s.length().

Multiple parameters are separated by commas: (a, b) -> a + b. When the body is a single expression, no return is needed; Java returns the result automatically. With a block body return is required: (a, b) -> { return a + b; }.

Block lambda and return

When a lambda body needs multiple statements, you write a block with curly braces. Inside the block, a return statement returns the result. Example: (int a, int b) -> { int sum = a + b; return sum * 2; }.

Even with a single-line block body, return is required: (a, b) -> { return a + b; }. This differs from an expression body, where return is omitted. Mixing the two styles by mistake causes a compile error.

Practice A two-number adder lambda

Define java.util.function.BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b;. Call it with int result = add.apply(3, 4);. Print the result with System.out.println(result);.

Starter code

Main.java
import java.util.function.BiFunction;

public class Main {
    public static void main(String[] args) {
        // Define a BiFunction<Integer, Integer, Integer> lambda, call apply, print

    }
}

Sample solution

Main.java
import java.util.function.BiFunction;

public class Main {
    public static void main(String[] args) {
        BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b;
        int result = add.apply(3, 4);
        System.out.println(result);
    }
}

Expected output

7

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the single-parameter lambda

Question
java.util.function.Function<String, Integer> len = ____ -> s.length();
Answer
java.util.function.Function<String, Integer> len = s -> s.length();

Explanation: With one parameter parentheses are optional.

2 What does (a, b) -> a + b return?

  • A Runnable instance
  • Throws an error
  • The sum of a and b Correct answer
  • Prints a and b

Explanation: An expression body returns the result automatically; the sum is returned.

3 Match the lambda body types

Term Meaning
() -> ... No parameters
s -> ... Single parameter
(a, b) -> ... Two parameters
{ return ...; } Block body

All lessons in Intermediate