← Back to Home

Lambda Expressions

Lambda expressions introduce a concise, functional style of programming in Java. They enable you to represent behavior as data, drastically reducing boilerplate code and improving readability—especially with collections, streams, and concurrency.

This is a very high-frequency interview topic (Java 8+).

What Is a Lambda Expression?

A lambda expression is an anonymous function—a block of code that:

  • Has no name
  • Can be passed as an argument
  • Can be executed later

It is primarily used to implement functional interfaces.

Basic Syntax

(parameters) -> expression
or

(parameters) -> {
    statements;
}
          

Examples

() -> System.out.println("Hello");

(a, b) -> a + b

(int a, int b) -> {
    return a * b;
}
          

Functional Interface (Foundation of Lambdas)

A functional interface has exactly one abstract method.

@FunctionalInterface
interface Calculator {
    int add(int a, int b);
}
          
  • ✔ Can have default and static methods
  • ✔ @FunctionalInterface is optional but recommended

Lambda with Functional Interface

Without Lambda (Old Style)

Calculator c = new Calculator() {
    public int add(int a, int b) {
        return a + b;
    }
};
          

With Lambda (Java 8+)

Calculator c = (a, b) -> a + b;
          
  • ✔ Cleaner
  • ✔ Readable
  • ✔ Less boilerplate

Common Built-in Functional Interfaces

Interface Method Purpose
Runnable run() No input, no output
Consumer<T> accept(T) Input, no output
Supplier<T> get() No input, output
Function<T, R> apply(T) Input → output
Predicate<T> test(T) Boolean condition

Examples

Runnable r = () -> System.out.println("Running");

Predicate isEven = n -> n % 2 == 0;

Function length = s -> s.length();
          

Lambda with Collections (Very Common)

Iterating a List

List list = Arrays.asList("Java", "Python", "C++");
list.forEach(s -> System.out.println(s));
          

Sorting with Lambda

Collections.sort(list, (a, b) -> a.compareTo(b));
          

Lambda with Threads

Thread t = new Thread(() -> {
    System.out.println("Thread running");
});
t.start();
          
  • ✔ Uses Runnable internally
  • ✔ Preferred modern approach

Parameter Rules

(a, b) -> a + b          // type inferred
(int a, int b) -> a + b // explicit type
❌ Mixing typed and untyped parameters is not allowed
          

Lambda Body Rules

  • Single statement → braces optional
  • Multiple statements → braces + return required
a -> a * a

a -> {
    int result = a * a;
    return result;
}
          

Variable Capture (Effectively Final)

Lambdas can access local variables only if they are final or effectively final.

int x = 10;
Runnable r = () -> {
    System.out.println(x);
};
❌ Modifying x later → compilation error
          

this Keyword in Lambda (Interview Trap)

  • this refers to enclosing class, not lambda
  • Unlike anonymous inner classes
this.toString(); // enclosing object
          

Lambda vs Anonymous Inner Class

Aspect Lambda Anonymous Class
Code size Minimal Verbose
this reference Enclosing class Inner class
Readability High Low
Performance Better Slight overhead

Where Lambdas Are Used Heavily

  • Streams API
  • Collections sorting/filtering
  • Event handling
  • Concurrency (Runnable, Callable)
  • Functional-style programming

Limitations of Lambda Expressions

  • Can be used only with functional interfaces
  • Cannot have state (no instance variables)
  • Cannot throw checked exceptions directly (without handling)
  • Overuse can reduce readability if complex

Common Beginner Mistakes

  • Trying to use lambda with non-functional interfaces
  • Writing complex logic inside lambda
  • Confusing this behavior
  • Ignoring readability
  • Forgetting variable must be effectively final

Interview-Ready Answers

Short Answer

Lambda expressions provide a concise way to implement functional interfaces in Java.

Detailed Answer

In Java, lambda expressions are anonymous functions used to implement functional interfaces. Introduced in Java 8, they reduce boilerplate code, improve readability, and enable functional programming features such as streams and parallel processing.

Key Takeaway

Lambda expressions = behavior as data. They make Java cleaner, more expressive, and functional, especially when combined with functional interfaces and streams.