01 / 21
\(\lambda\)

Lambda
Expressions

Master the art of writing concise, expressive code using Java's lambda syntax: anonymous functions that bring functional programming to your toolkit.

Java Functional Programming

What Is a Lambda Expression?

A lambda expression is a short block of code that takes parameters and returns a value. Think of it as an anonymous function: a method without a name that you can pass around like a variable.

Anonymous
No name needed: defined right where it is used
Concise
Replace verbose inner classes with a single line
Passable
Treat behavior as data: pass it to methods

Why Do Lambdas Matter?

Before Java 8, passing behavior required creating an entire anonymous inner class. Lambdas let you express the same idea in far fewer lines, making your code easier to read and maintain.

Before (Anonymous Class)
Runnable r = new Runnable() {
  @Override
  public void run() {
    System.out.println(
      "Hello");
  }
};
→ After (Lambda)
Runnable r = () ->
  System.out.println("Hello");
7 lines 1 line

Functional Interfaces: The Foundation

A lambda expression can only be used where Java expects a functional interface: an interface with exactly one abstract method. The lambda provides the implementation of that method.

@FunctionalInterface public interface Greeting { void sayHello(String name); }

Anatomy of a Lambda

( parameters ) -> expression Input(s) What the lambda receives Arrow Operator Body What the lambda does
1
Parameters: zero or more inputs, inside parentheses. Types are often inferred.
2
Arrow operator ->: separates parameters from the body.
3
Body: a single expression (auto-returned) or a block { ... } with an explicit return.

Syntax Variations

No Parameters
() -> 42
Empty parens required
One Parameter
x -> x * 2
Parens optional for one param
Multiple Params
(a, b) -> a + b
Parens required, comma-separated
Block Body
(x) -> { return x * x; }
Braces + explicit return
With Types
(int a, int b) -> a + b
Explicit type declarations

Lambda vs Anonymous Class

Lambda Expression Anonymous Inner Class
Syntax Concise: 1-2 lines Verbose: 5+ lines
Target Functional interfaces only Any interface or abstract class
this keyword Refers to enclosing class Refers to the inner class itself
Compiled as invokedynamic Separate .class file
Performance Faster (less overhead) Slower (class loading)

How to Write a Lambda

1
Identify the functional interface. What method signature does the target require? Check parameters and return type.
2
Write the parameter list. Match the abstract method's parameters. Omit types if the compiler can infer them.
3
Add the arrow. Place -> after the parameters.
4
Write the body. Single expression: written directly. Multiple statements: wrap in { } and use return if needed.
5
Assign or pass. Store in a variable of the interface type, or pass directly to a method that expects it.

Example 1: Sorting with a Lambda

The Comparator interface has one abstract method: compare(T a, T b). This makes it a perfect target for a lambda.

List<String> names = Arrays.asList("Zara", "Ana", "Mia"); // Sort alphabetically using a lambda names.sort((a, b) -> a.compareTo(b)); // Result: [Ana, Mia, Zara]

Example 2: Iterating with forEach

The forEach method accepts a Consumer<T>: a functional interface whose abstract method accept(T t) takes one parameter and returns nothing.

List<Integer> nums = List.of(1, 2, 3, 4, 5); // Print each number doubled nums.forEach(n -> System.out.print(n * 2 + " ")); // Output: 2 4 6 8 10

Example 3: Filtering with Predicate

Predicate<T> has one abstract method: test(T t), which returns a boolean. It is the go-to interface for filter conditions.

List<String> words = List.of("hi", "hello", "hey", "howdy"); // Keep only words longer than 3 characters List<String> longWords = words.stream() .filter(w -> w.length() > 3) .collect(Collectors.toList()); // Result: [hello, howdy]

Java's Built-in Functional Interfaces

Interface Abstract Method Use Case
Predicate<T> test(T) -> boolean Filtering, conditions
Function<T,R> apply(T) -> R Transformations, mapping
Consumer<T> accept(T) -> void forEach, side effects
Supplier<T> get() -> T Lazy generation, factories
Comparator<T> compare(T,T) -> int Sorting, ordering

Block Body: Multiple Statements

When the lambda body needs more than one statement, wrap it in curly braces. If the interface method has a return type, you must include an explicit return statement.

Function<Integer, String> classify = (n) -> { if (n > 0) { return "positive"; } else if (n < 0) { return "negative"; } else { return "zero"; } }; classify.apply(-5); // "negative"

Variable Capture

Lambdas can capture variables from the surrounding scope, but those variables must be effectively final: assigned once and never modified after.

String prefix = "Hello, "; // effectively final Consumer<String> greet = name -> System.out.println(prefix + name); greet.accept("World"); // Hello, World // prefix = "Hi, "; <- COMPILE ERROR!

Common Mistakes

Missing Return
Using braces { } but forgetting the return keyword. The compiler expects a return if the method has a non-void return type.
Wrong Interface
Trying to use a lambda with an interface that has multiple abstract methods. Lambdas only work with functional interfaces.
Modifying Captured Variables
Reassigning a local variable that the lambda references. Captured variables must be effectively final.

Lambda Quick Reference

Pattern Syntax Example
No params () -> expr () -> 42
One param x -> expr x -> x * 2
Two params (a, b) -> expr (a, b) -> a + b
Block body (x) -> { ... } (x) -> { return x; }
With types (T x) -> expr (int x) -> x + 1

Question 1 of 5

Which of the following is the correct lambda expression for a Comparator<String> that compares strings by length?

Question 2 of 5

A functional interface in Java is an interface that has:

Question 3 of 5

What does the following code print?

List<Integer> nums = List.of(1, 2, 3); nums.forEach(n -> System.out.print(n * 3 + " "));

Question 4 of 5

Which lambda syntax is invalid in Java?

Question 5 of 5

Why does the following code fail to compile?

int count = 0; List<String> names = List.of("A", "B", "C"); names.forEach(name -> count++);