Lambda Expressions in Java: Explained in Easy Steps

A lambda expression in Java provides a clear and concise way to represent an anonymous function — a block of code that can be passed around and executed later. Lambdas were introduced in Java 8 to support functional programming.

Syntax

(parameters) -> expression
// or
(parameters) -> { statements; }

Step 1: Without Lambda (Traditional Way)

Runnable r = new Runnable() {
    public void run() {
        System.out.println("Running without lambda");
    }
};

Step 2: With Lambda

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

Step 3: Lambda With Parameters

interface Calculator {
    int add(int a, int b);
}

Calculator calc = (a, b) -> a + b;
System.out.println(calc.add(5, 3)); // Output: 8

Step 4: Using Lambdas With Built-in Functional Interfaces

import java.util.function.Function;

Function<Integer, Integer> square = n -> n * n;
System.out.println(square.apply(6)); // Output: 36

Step 5: Lambdas With Collections

List<String> names = Arrays.asList("Riya", "Aman", "Karan");
names.forEach(name -> System.out.println(name));

What is a Functional Interface?

A lambda expression can only be used where a functional interface is expected — an interface with exactly one abstract method, such as Runnable, Comparator, or Function.

Why Use Lambda Expressions?

  • Reduces boilerplate code compared to anonymous inner classes
  • Makes code more readable, especially when working with collections and streams
  • Enables a functional programming style alongside Java's object-oriented approach
Lambda expressions are the foundation of the Streams API introduced in Java 8, which lets you process collections in a declarative, pipeline-like style.

Master Java with Uncodemy

Hands-on training, live projects, and placement support in our Java Programming Course.

Explore the Course