Java Lambda Basics

Su Suriya Ravichandran Updated 18 Nov 2026
10 min read ·Lesson 167 of 306

What a Lambda Expression Is

A lambda expression is a short block of code that you can pass around like a value — store it in a variable, pass it to a method, return it from a method — and run later. It's often described as an anonymous function: a function with parameters and a body, but no name and no class of its own.

(a, b) -> Integer.compare(a.length(), b.length())

This lambda takes two parameters, a and b, and returns the result of comparing their lengths. On its own it does nothing; it's a piece of behaviour that some other code will call.

Lambdas were added in Java 8 (2014). They made it practical to write code that is customised by passing in behaviour — sort this way, keep items that match this rule, run this action when an event happens — and they're the foundation of the Stream API covered later in this section.

The Problem Lambdas Solve

Before Java 8, passing behaviour meant creating an object of a class that implements an interface, usually an anonymous class. Here's the same sort written both ways:

import java.util.*;

public class Before {
    public static void main(String[] args) {
        List<String> cities = new ArrayList<>(List.of("Madurai", "Chennai", "Salem", "Coimbatore"));

        Collections.sort(cities, new Comparator<String>() {
            @Override
            public int compare(String a, String b) {
                return Integer.compare(a.length(), b.length());
            }
        });
        System.out.println("anonymous class: " + cities);

        cities.sort((a, b) -> Integer.compare(b.length(), a.length()));
        System.out.println("lambda:          " + cities);

        Runnable task = () -> System.out.println("running in " + Thread.currentThread().getName());
        task.run();
        new Thread(task, "worker-1").start();
    }
}

Output:

anonymous class: [Salem, Madurai, Chennai, Coimbatore]
lambda:          [Coimbatore, Madurai, Chennai, Salem]
running in main
running in worker-1
  • The anonymous class needs six lines of structure — new Comparator<String>(), @Override, the method signature, braces — around one line that matters: Integer.compare(a.length(), b.length()).
  • The lambda is just that line, plus the parameter names. The compiler works out everything else: that a Comparator<String> is needed, that the method is compare, that a and b are Strings, and that the result is returned. (This lambda sorts longest first, the reverse of the anonymous class.)
  • Runnable task = () -> ... stores behaviour in a variable. The same code runs once directly in the main thread and once in a new thread — the lambda is a value that can be handed to whoever needs it.

Lambdas Need a Functional Interface

A lambda doesn't have a type of its own. It always becomes an instance of a functional interface — an interface with exactly one abstract method. The lambda provides the implementation of that one method.

Functional interfaceIts single abstract methodExample lambda
Runnablevoid run()() -> System.out.println("hi")
Comparator<T>int compare(T a, T b)(a, b) -> a.length() - b.length()
Predicate<T>boolean test(T t)p -> p.stock() == 0
Function<T, R>R apply(T t)s -> s.length()
Consumer<T>void accept(T t)s -> System.out.println(s)
Supplier<T>T get()() -> new ArrayList<>()

The interface that the lambda becomes is determined by the context where it's written — the variable it's assigned to, or the parameter type of the method it's passed to. This is called the target type. The same lambda text can therefore become different types in different places, and a lambda can't appear where there is no target type (var f = x -> x * 2; doesn't compile, because the compiler has nothing to infer the type from).

The Functional Interfaces lesson covers these interfaces in detail, and the Lambda Syntax lesson covers all the forms a lambda can take.

Passing Behaviour as a Parameter

The real power of lambdas is behaviour parameterisation: writing one method whose logic is completed by a lambda supplied by the caller.

import java.util.*;
import java.util.function.Predicate;

public class Behaviour {
    record Product(String name, String category, double price, int stock) { }

    static List<Product> filter(List<Product> items, Predicate<Product> rule) {
        List<Product> result = new ArrayList<>();
        for (Product p : items) if (rule.test(p)) result.add(p);
        return result;
    }

    public static void main(String[] args) {
        List<Product> catalog = List.of(
            new Product("Gel pen", "stationery", 25, 400),
            new Product("Laptop bag", "bags", 1899, 3),
            new Product("Notebook", "stationery", 60, 0),
            new Product("Backpack", "bags", 1299, 18));

        System.out.println(names(filter(catalog, p -> p.stock() == 0)));
        System.out.println(names(filter(catalog, p -> p.category().equals("bags"))));
        System.out.println(names(filter(catalog, p -> p.price() < 100 && p.stock() > 0)));

        double budget = 1500;
        System.out.println(names(filter(catalog, p -> p.price() <= budget)));
    }

    static List<String> names(List<Product> ps) { return ps.stream().map(Product::name).toList(); }
}

Output:

[Notebook]
[Laptop bag, Backpack]
[Gel pen]
[Gel pen, Notebook, Backpack]
  • filter is written once. It loops over the products and keeps those for which rule.test(p) is true; it doesn't know or care what the rule is.
  • Each call supplies a different rule: out of stock, in the "bags" category, cheap and available, within budget. Without lambdas you'd either write four nearly identical methods (filterOutOfStock, filterBags, ...) or four anonymous classes.
  • Parameter types are inferred. Because filter expects a Predicate<Product>, the compiler knows p is a Product, so p.stock() and p.category() compile.
  • Lambdas can use local variables: the last rule reads budget from the surrounding method.

The JDK uses this design everywhere: List.removeIf(Predicate), List.sort(Comparator), Map.computeIfAbsent(key, Function), Iterable.forEach(Consumer), and the whole Stream API.

Capturing Variables: Effectively Final

A lambda can read local variables from the method around it — it captures them. There's one rule: captured local variables must be final or effectively final, meaning they're never assigned again after initialisation.

import java.util.function.*;

public class CapErr {
    public static void main(String[] args) {
        int total = 0;
        Runnable r = () -> total++;
        int limit = 10;
        limit = 20;
        Predicate<Integer> p = x -> x > limit;
    }
}
CapErr.java:6: error: local variables referenced from a lambda expression must be final or effectively final
        Runnable r = () -> total++;
                           ^
CapErr.java:9: error: local variables referenced from a lambda expression must be final or effectively final
        Predicate<Integer> p = x -> x > limit;
                                        ^
2 errors
  • total++ tries to modify a captured variable.
  • limit is reassigned before the lambda, so it's no longer effectively final — even though the lambda only reads it.

Why the rule exists: a lambda can run later, and even on a different thread, after the method that created it has returned. Local variables live on the method's stack, which disappears when the method returns, so the lambda receives a copy of the value. If the variable could change afterwards, the lambda's copy and the variable would disagree, and with threads the result would be unpredictable. Requiring effectively final variables makes the copy indistinguishable from the original.

What's allowed:

import java.util.*;
import java.util.function.*;

public class Capture {
    public static void main(String[] args) {
        int threshold = 50;
        Predicate<Integer> passed = mark -> mark >= threshold;
        System.out.println(passed.test(72) + " " + passed.test(41));

        int[] counter = {0};
        Runnable increment = () -> counter[0]++;
        increment.run();
        increment.run();
        System.out.println("counter: " + counter[0]);

        List<Supplier<String>> greeters = new ArrayList<>();
        for (String name : List.of("Asha", "Ravi")) {
            greeters.add(() -> "Hello, " + name);
        }
        greeters.forEach(g -> System.out.println(g.get()));
    }
}

Output:

true false
counter: 2
Hello, Asha
Hello, Ravi
  • Reading an effectively final variable (threshold) is the normal case.
  • Modifying the contents of an object is allowed: counter itself never changes — it always refers to the same array — but the array's element does. This workaround is fine for simple single-threaded code; it isn't thread-safe, and in stream code a sum() or count() is the better tool.
  • The enhanced for loop variable is a new variable on each iteration, so it's effectively final and each lambda captures its own name. (A classic for (int i = 0; ...; i++) counter is not, because i++ reassigns it.)
  • Fields (instance and static variables) aren't subject to this rule — they're accessed through the object, not copied.

this Inside a Lambda

A lambda isn't an object of a new class in the way an anonymous class is. Inside a lambda, this means the same as in the surrounding method:

public class This {
    private final String name = "outer object";

    void show() {
        Runnable lambda = () -> System.out.println("lambda this:    " + this.name);
        Runnable anon = new Runnable() {
            private final String name = "anonymous object";
            @Override public void run() { System.out.println("anonymous this: " + this.name); }
        };
        lambda.run();
        anon.run();
    }

    public static void main(String[] args) {
        new This().show();
    }
}

Output:

lambda this:    outer object
anonymous this: anonymous object
  • In the lambda, this is the This object whose show() method created it.
  • In the anonymous class, this is the anonymous class's own instance, which has its own fields.

This makes lambdas easier to reason about: their body reads like code in the enclosing method. Lambdas also can't declare fields or have state of their own; when you need that, an anonymous class or a named class is the right tool.

When to Use Lambdas — and When Not To

Use a lambda when:

  • an API expects a functional interface (sorting, filtering, event handlers, callbacks, tasks for executors, stream operations);
  • the behaviour is short and its meaning is clear at the point of use.

Prefer a named method or class when:

  • the logic is longer than a few lines or needs a name to be understood — write a method and refer to it with a method reference (this::isEligible, see the Method References lesson);
  • the same logic is used in many places;
  • the implementation needs its own fields, multiple methods, or must implement an interface with several abstract methods;
  • the behaviour needs to be tested in isolation.

Lambdas that span many lines inside a method call quickly become hard to read and hard to debug (stack traces show synthetic names like lambda$main$0).

Practical Example: Order Event Notifications

When an order is placed, several independent things should happen: an email confirmation, an SMS for express orders, an alert to the sales team for large orders. Registering each reaction as a lambda keeps the order-placing code unaware of what the reactions are, and new reactions can be added without changing it.

import java.util.*;
import java.util.function.*;

public class Notify {
    record Order(String id, String customer, String phone, String email, double amount, boolean express) { }

    static class OrderEvents {
        private final List<Consumer<Order>> onPlaced = new ArrayList<>();
        void whenPlaced(Consumer<Order> action) { onPlaced.add(action); }
        void place(Order o) {
            System.out.println("placed " + o.id());
            onPlaced.forEach(action -> action.accept(o));
        }
    }

    public static void main(String[] args) {
        OrderEvents events = new OrderEvents();
        List<String> outbox = new ArrayList<>();
        double highValue = 10_000;

        events.whenPlaced(o -> outbox.add("EMAIL to " + o.email() + ": order " + o.id() + " confirmed"));
        events.whenPlaced(o -> {
            if (o.express()) outbox.add("SMS to " + o.phone() + ": express order " + o.id() + " ships today");
        });
        events.whenPlaced(o -> {
            if (o.amount() >= highValue) outbox.add("SLACK #sales: big order " + o.id() + " from " + o.customer());
        });

        events.place(new Order("O-1001", "Asha", "+91-90000-11111", "asha@gocourse.in", 2_499, true));
        events.place(new Order("O-1002", "Ravi", "+91-90000-22222", "ravi@gocourse.in", 18_750, false));
        outbox.forEach(m -> System.out.println("  " + m));
    }
}

Output:

placed O-1001
placed O-1002
  EMAIL to asha@gocourse.in: order O-1001 confirmed
  SMS to +91-90000-11111: express order O-1001 ships today
  EMAIL to ravi@gocourse.in: order O-1002 confirmed
  SLACK #sales: big order O-1002 from Ravi

How it works:

  1. Consumer<Order> is a functional interface whose method accept(Order) returns nothing — the right shape for "do something with this order".
  2. whenPlaced stores each lambda in a list. The lambdas are objects that will be called later, when an order is placed.
  3. place runs every registered action with onPlaced.forEach(action -> action.accept(o)) — itself a lambda passed to forEach.
  4. Each reaction is independent. The SMS lambda checks o.express(); the sales alert checks the amount against highValue, a captured, effectively final local variable. Lambdas with several statements use a block body { ... }.
  5. Captured state. All three lambdas add to the same outbox list. The variable outbox is effectively final; the list it refers to is modified, which is allowed. A real application would send the messages through email and SMS services instead of collecting them.

This is the observer pattern. Before Java 8 it required an interface plus a class (or anonymous class) per reaction; with lambdas, each reaction is one short expression next to the others, which is how GUI event handlers, Spring's event listeners and many callback-based APIs are used today.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Lambda Basics and get answers drawn from it.

Signed-in readers only.