Command Palette

Search for a command to run...

Back to the lesson: Topic 10.1 — Lambda Expressions
Core Java · Example 2 of 4 Java 11+

Every lambda shape, and passing behaviour to a method

applyTwice doesn't know what f does. The caller decides, by passing different lambdas.

A lambda expression is a short, nameless function you can store in a variable or pass to a method, like (a, b) -> a + b. It always becomes an object of a functional interface type, and it can read local variables only if they are effectively final.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write static void repeat(int times, Runnable action) and use it to print Hello 1, Hello 2, Hello 3 using a counter held in an int[].

02

Sort List.of("kiwi", "fig", "banana", "apple") (copied into an ArrayList) by length, and alphabetically for equal lengths, using one lambda comparator. Print the list.

03

Write static Function<Integer, Integer> adder(int n) that returns a lambda adding n. Create add5 and add10 and print add5.apply(1), add10.apply(1) and add5.apply(add10.apply(0)).

Explain it without notes

01

What is a lambda expression, and what decides its type?

02

Why must captured local variables be effectively final, while fields can change?

03

How does this behave inside a lambda compared with an anonymous class?

04

How does the JVM create a lambda object at runtime?

Every lambda shape, and passing behaviour to a method Java 11+
Sign in to run this example in your browser.

Expected output

no parameters
12
5
20
5
42 is big
applyTwice: 18
applyTwice inline: 201