1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Lambda Expressions
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
03Hrs
37Mins
52Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Lambda Expressions

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
03Hrs
37Mins
52Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

Lambda Expressions

Overview

Lambda Expressions were the headline feature of Java 8 and fundamentally changed how Java code is written. Before Java 8, passing behavior (a function) as a parameter to another method required creating a verbose anonymous inner class. Lambdas provide a clean, concise syntax to do this with minimal boilerplate.

A Lambda Expression is, at its core, an anonymous function — a function without a name, without a class, and without a return statement (for single expressions). The arrow syntax (parameters) -> expression defines the behavior inline. Lambdas can be used wherever a Functional Interface is expected. A Functional Interface is any interface that has exactly one abstract method (like Runnable, Comparator, or any @FunctionalInterface annotated interface).

Java 8 also introduced the java.util.function package with four primary built-in Functional Interfaces: - `Predicate<T>`: Takes a T, returns a boolean (test(T t)). - `Function<T, R>`: Takes a T, returns an R (apply(T t)). - `Consumer<T>`: Takes a T, returns nothing (accept(T t)). - `Supplier<T>`: Takes nothing, returns a T (get()).

Syntax

Notice that with Predicate, Function, Consumer, and Supplier you can express almost any transformation or check on data. These are the building blocks of the Streams API.

Lambda Syntax and Built-in Functional Interfaces
java
import java.util.*;
import java.util.function.*;

public class Main {
    public static void main(String[] args) {
        // 1. Before Lambda: Verbose Anonymous Class
        Comparator<String> oldWay = new Comparator<String>() {
            @Override
            public int compare(String a, String b) {
                return a.compareTo(b);
            }
        };
        
        // 2. After Lambda: Clean and Concise
        Comparator<String> newWay = (a, b) -> a.compareTo(b);
        
        // 3. The 4 Core Functional Interfaces
        
        // Predicate<T>: Takes T, returns boolean
        Predicate<Integer> isEven = n -> n % 2 == 0;
        System.out.println(isEven.test(4)); // true
        
        // Function<T, R>: Takes T, returns R
        Function<String, Integer> strToLength = s -> s.length();
        System.out.println(strToLength.apply("Java")); // 4
        
        // Consumer<T>: Takes T, returns nothing
        Consumer<String> printer = s -> System.out.println("-> " + s);
        printer.accept("Hello Lambda!"); // -> Hello Lambda!
        
        // Supplier<T>: Takes nothing, returns T
        Supplier<String> greeting = () -> "Good morning!";
        System.out.println(greeting.get()); // Good morning!
        
        // 4. Practical: Sorting a list with Lambda
        List<String> names = new ArrayList<>(List.of("Charlie", "Alice", "Bob"));
        names.sort((a, b) -> a.compareTo(b));
        System.out.println(names); // [Alice, Bob, Charlie]
    }
}

Common Pitfalls

  • Using lambdas where a method reference would be clearer. s -> System.out.println(s) can and should be written as the method reference System.out::println. Method references are more readable and compile to slightly more efficient bytecode.
  • Trying to modify local variables from the enclosing scope. Lambdas can only read local variables from the surrounding method if those variables are final or effectively final (never reassigned). Trying to write int count = 0; list.forEach(e -> count++); will fail to compile because count is being mutated.
  • Catching checked exceptions inside lambda expressions. If a lambda body calls a method that throws a Checked Exception, the lambda must handle it, but it cannot declare throws in its signature. The common workaround is to wrap checked exceptions in a RuntimeException, or use a helper FunctionWithException wrapper interface.

Interview Questions

What is a Functional Interface and why is it required for lambdas?

A Functional Interface is any interface with exactly one abstract method (SAM — Single Abstract Method). Lambdas work by providing the implementation of that single method. The compiler uses the Functional Interface as the target type, resolving exactly which one abstract method the lambda is implementing. If an interface had two abstract methods, the compiler wouldn't know which one the lambda is implementing.

What is the difference between a Lambda and a Method Reference?

A Method Reference (ClassName::methodName) is a more concise notation for a lambda that simply calls an existing method without any additional logic. s -> s.toUpperCase() is functionally identical to String::toUpperCase. Method references are preferred when the lambda body contains only a single method call on the parameter.

Are lambdas in Java truly anonymous functions, or are they secretly objects?

They are effectively objects at runtime, but not created via anonymous classes. Lambda expressions are compiled to invokedynamic bytecode instructions (Java 7+ JVM feature). The first time a lambda is invoked, the JVM generates a tiny class for it. Subsequent invocations reuse the generated class. This makes lambdas significantly faster than traditional anonymous inner classes.

Real-World Example

Modern Spring Boot applications use lambdas pervasively in security configuration, routing, and validation. The entire Spring Security DSL is built on chaining lambdas, eliminating hundreds of lines of XML or class-based configuration.

example
java
// Spring Security 6 configuration using lambdas
@Bean
public SecurityFilterChain securityChain(HttpSecurity http) throws Exception {
    return http
        .authorizeHttpRequests(auth -> auth
            .requestMatchers("/api/public/**").permitAll()
            .anyRequest().authenticated()
        )
        .sessionManagement(session -> session
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        )
        .build();
}

Check Your Knowledge

Test your understanding of Lambda Expressions with these quick questions.

Question 1

What is the minimum number of abstract methods an interface must have to be used as a Lambda target type?

Question 2

Which built-in Functional Interface takes one argument and returns a boolean?

Question 3

Why does modifying a local variable from inside a lambda cause a compilation error?

Take Java Quiz
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

Lambda Expressions

Overview

Lambda Expressions were the headline feature of Java 8 and fundamentally changed how Java code is written. Before Java 8, passing behavior (a function) as a parameter to another method required creating a verbose anonymous inner class. Lambdas provide a clean, concise syntax to do this with minimal boilerplate.

A Lambda Expression is, at its core, an anonymous function — a function without a name, without a class, and without a return statement (for single expressions). The arrow syntax (parameters) -> expression defines the behavior inline. Lambdas can be used wherever a Functional Interface is expected. A Functional Interface is any interface that has exactly one abstract method (like Runnable, Comparator, or any @FunctionalInterface annotated interface).

Java 8 also introduced the java.util.function package with four primary built-in Functional Interfaces: - `Predicate<T>`: Takes a T, returns a boolean (test(T t)). - `Function<T, R>`: Takes a T, returns an R (apply(T t)). - `Consumer<T>`: Takes a T, returns nothing (accept(T t)). - `Supplier<T>`: Takes nothing, returns a T (get()).

Syntax

Notice that with Predicate, Function, Consumer, and Supplier you can express almost any transformation or check on data. These are the building blocks of the Streams API.

Lambda Syntax and Built-in Functional Interfaces
java
import java.util.*;
import java.util.function.*;

public class Main {
    public static void main(String[] args) {
        // 1. Before Lambda: Verbose Anonymous Class
        Comparator<String> oldWay = new Comparator<String>() {
            @Override
            public int compare(String a, String b) {
                return a.compareTo(b);
            }
        };
        
        // 2. After Lambda: Clean and Concise
        Comparator<String> newWay = (a, b) -> a.compareTo(b);
        
        // 3. The 4 Core Functional Interfaces
        
        // Predicate<T>: Takes T, returns boolean
        Predicate<Integer> isEven = n -> n % 2 == 0;
        System.out.println(isEven.test(4)); // true
        
        // Function<T, R>: Takes T, returns R
        Function<String, Integer> strToLength = s -> s.length();
        System.out.println(strToLength.apply("Java")); // 4
        
        // Consumer<T>: Takes T, returns nothing
        Consumer<String> printer = s -> System.out.println("-> " + s);
        printer.accept("Hello Lambda!"); // -> Hello Lambda!
        
        // Supplier<T>: Takes nothing, returns T
        Supplier<String> greeting = () -> "Good morning!";
        System.out.println(greeting.get()); // Good morning!
        
        // 4. Practical: Sorting a list with Lambda
        List<String> names = new ArrayList<>(List.of("Charlie", "Alice", "Bob"));
        names.sort((a, b) -> a.compareTo(b));
        System.out.println(names); // [Alice, Bob, Charlie]
    }
}

Common Pitfalls

  • Using lambdas where a method reference would be clearer. s -> System.out.println(s) can and should be written as the method reference System.out::println. Method references are more readable and compile to slightly more efficient bytecode.
  • Trying to modify local variables from the enclosing scope. Lambdas can only read local variables from the surrounding method if those variables are final or effectively final (never reassigned). Trying to write int count = 0; list.forEach(e -> count++); will fail to compile because count is being mutated.
  • Catching checked exceptions inside lambda expressions. If a lambda body calls a method that throws a Checked Exception, the lambda must handle it, but it cannot declare throws in its signature. The common workaround is to wrap checked exceptions in a RuntimeException, or use a helper FunctionWithException wrapper interface.

Interview Questions

What is a Functional Interface and why is it required for lambdas?

A Functional Interface is any interface with exactly one abstract method (SAM — Single Abstract Method). Lambdas work by providing the implementation of that single method. The compiler uses the Functional Interface as the target type, resolving exactly which one abstract method the lambda is implementing. If an interface had two abstract methods, the compiler wouldn't know which one the lambda is implementing.

What is the difference between a Lambda and a Method Reference?

A Method Reference (ClassName::methodName) is a more concise notation for a lambda that simply calls an existing method without any additional logic. s -> s.toUpperCase() is functionally identical to String::toUpperCase. Method references are preferred when the lambda body contains only a single method call on the parameter.

Are lambdas in Java truly anonymous functions, or are they secretly objects?

They are effectively objects at runtime, but not created via anonymous classes. Lambda expressions are compiled to invokedynamic bytecode instructions (Java 7+ JVM feature). The first time a lambda is invoked, the JVM generates a tiny class for it. Subsequent invocations reuse the generated class. This makes lambdas significantly faster than traditional anonymous inner classes.

Real-World Example

Modern Spring Boot applications use lambdas pervasively in security configuration, routing, and validation. The entire Spring Security DSL is built on chaining lambdas, eliminating hundreds of lines of XML or class-based configuration.

example
java
// Spring Security 6 configuration using lambdas
@Bean
public SecurityFilterChain securityChain(HttpSecurity http) throws Exception {
    return http
        .authorizeHttpRequests(auth -> auth
            .requestMatchers("/api/public/**").permitAll()
            .anyRequest().authenticated()
        )
        .sessionManagement(session -> session
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        )
        .build();
}

Check Your Knowledge

Test your understanding of Lambda Expressions with these quick questions.

Question 1

What is the minimum number of abstract methods an interface must have to be used as a Lambda target type?

Question 2

Which built-in Functional Interface takes one argument and returns a boolean?

Question 3

Why does modifying a local variable from inside a lambda cause a compilation error?

Take Java Quiz

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A