← Back to Advanced Java Course | Chapter 3: Functional Programming | Lesson 1 of 6

Java Lambda Expressions

A lambda expression is a short nameless function you write in one line, like a quick sticky-note instruction. It is handy for small pieces of behavior.
Syntax
java
(parameters) -> expression

(parameters) -> {
    // statements
    return value;
}

What is a Lambda Expression?

Lambda expressions are anonymous, unnamed functions that simplify your code by eliminating the boilerplate of writing a full class just to pass around a single behavior. They let you treat a piece of functionality as a method argument, essentially treating code itself as data you can pass around.

Example: What is a Lambda Expression?

java
// Define the class Main
public class Main {
	// Define the interface Greeting
	interface Greeting {
		void greet();
	}
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		Greeting g = () -> System.out.println("Hello from a lambda");
		g.greet();
	}
}

Lambda with Parameters

You can pass parameters to a lambda expression by declaring them inside the parentheses on the left side of the arrow (->) operator, just like a normal method's parameter list, except Java can usually infer their types automatically.

Example: Lambda with Parameters

java
// Define the class Main
public class Main {
	// Define the interface Adder
	interface Adder {
		int add(int a, int b);
	}
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		Adder adder = (a, b) -> a + b;
		// Print a line to the console
		System.out.println(adder.add(3, 4));
	}
}

Lambda with Return Values

If a lambda body contains only a single expression, Java automatically returns its value without requiring an explicit return keyword, keeping one-liners compact. For multi-statement bodies, wrap the code in curly braces and write an explicit return statement, just like an ordinary method.

Example: Lambda with Return Values

java
public class Main {
	interface Square {
		int of(int n);
	}
	public static void main(String[] args) {
		Square oneLiner = n -> n * n; // implicit return
		Square multiLine = n -> {
			int result = n * n;
			return result;
		};
		System.out.println(oneLiner.of(4) + " " + multiLine.of(5));
	}
}

Lambdas and Variable Scope

Lambda expressions can freely read instance or static variables from their enclosing scope, but they can only capture local variables that are declared final or are effectively final, meaning never reassigned after initialization. This restriction exists because the lambda may run later, on a different thread, after the original local variable would otherwise have gone out of scope.

Example: Lambdas and Variable Scope

java
public class Main {
	interface Printer {
		void print();
	}
	public static void main(String[] args) {
		final int count = 10; // effectively final, safe to capture
		Printer p = () -> System.out.println("Count is " + count);
		p.print();
	}
}

Common Use Cases

Lambda expressions are most commonly used to write concise collection iteration, filtering predicates, or custom sorting comparators inline, right where they're needed, instead of as separate named classes scattered elsewhere in the codebase.

Example: Common Use Cases

java
import java.util.*;
public class Main {
	public static void main(String[] args) {
		List<Integer> nums = new ArrayList<>(List.of(5, 3, 8, 1));
		nums.removeIf(n -> n < 4); // filtering predicate
		nums.sort((a, b) -> b - a); // custom comparator
		System.out.println(nums);
	}
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Modifying a local variable from inside a lambda, like count++, which does not compile because captured locals must be final or effectively final.
  2. Using a lambda where the target type is not a functional interface, such as var f = () -> 5; or an interface with two abstract methods.
  3. Thinking this inside a lambda refers to the lambda, when it refers to the enclosing class instance.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.