Java Lambda Syntax

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

The Parts of a Lambda

Every lambda expression has three parts:

(parameters)  ->  body
PartMeaning
Parameter listThe inputs, matching the parameters of the functional interface's single abstract method
Arrow ->Separates the parameters from the body
BodyEither a single expression or a block of statements in braces

The parameter types and return type come from the target type — the functional interface the lambda is assigned or passed to — so most of the time you don't write them. The rest of this lesson covers every allowed form and the rules that go with them.

All the Forms

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

public class Forms {
    public static void main(String[] args) {
        Supplier<String> greeting = () -> "Vanakkam";
        Function<String, Integer> length = s -> s.length();
        Function<String, Integer> length2 = (s) -> s.length();
        BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b;
        BiFunction<Integer, Integer, Integer> addTyped = (Integer a, Integer b) -> a + b;
        BiFunction<Integer, Integer, Integer> addVar = (var a, var b) -> a + b;

        Function<Double, String> grade = mark -> {
            if (mark >= 90) return "A";
            if (mark >= 75) return "B";
            return "C";
        };
        Consumer<String> log = msg -> System.out.println("[log] " + msg);
        Runnable beep = () -> { };

        System.out.println(greeting.get() + " " + length.apply("Java") + " " + length2.apply("Go"));
        System.out.println(add.apply(2, 3) + " " + addTyped.apply(4, 5) + " " + addVar.apply(6, 7));
        System.out.println(grade.apply(93.5) + grade.apply(80.0) + grade.apply(40.0));
        log.accept("syntax works");
        beep.run();
    }
}

Output:

Vanakkam 4 2
5 9 13
ABC
[log] syntax works

Parameters

FormExampleNotes
No parameters() -> "Vanakkam"Empty parentheses are required
One parameter, no types -> s.length()Parentheses are optional for exactly one untyped parameter
One parameter in parentheses(s) -> s.length()Same meaning
Several parameters(a, b) -> a + bParentheses required
Explicit types(Integer a, Integer b) -> a + bRarely needed; useful when inference fails or for clarity
var (Java 11+)(var a, var b) -> a + bInferred types, but allows annotations such as (@NonNull var a, var b)

Parameter names are your choice and don't have to match the interface's parameter names. Use short names for short lambdas (s, p, a, b) and descriptive ones when the meaning isn't obvious ((order, customer) -> ...).

A lambda parameter can't have the same name as a local variable already in scope — String s = "x"; Function<String, Integer> f = s -> s.length(); doesn't compile — because lambdas don't introduce a new scope for names the way an anonymous class does.

Body

  • Expression body: a + b. The value of the expression is returned automatically; there's no return keyword and no semicolon inside.
  • Block body: { statements }. Use it for several statements. If the interface method returns a value, every path must end in return value; — as in grade. If it returns void, return; is optional.
  • Empty block: () -> { } is a valid Runnable that does nothing.

Syntax Rules the Compiler Enforces

import java.util.function.*;

public class Errs {
    public static void main(String[] args) {
        BiFunction<Integer, Integer, Integer> mixed = (Integer a, b) -> a + b;
        BiFunction<Integer, Integer, Integer> mixedVar = (var a, Integer b) -> a + b;
    }
}
Errs.java:5: error: invalid lambda parameter declaration
        BiFunction<Integer, Integer, Integer> mixed = (Integer a, b) -> a + b;
                                                      ^
  (cannot mix implicitly-typed and explicitly-typed parameters)
Errs.java:6: error: invalid lambda parameter declaration
        BiFunction<Integer, Integer, Integer> mixedVar = (var a, Integer b) -> a + b;
                                                         ^
  (cannot mix 'var' and explicitly-typed parameters)

All parameters must use the same style: all untyped, all explicitly typed, or all var.

A block body for a non-void method must return a value on every path:

Function<Integer, String> noReturn = n -> { String s = "#" + n; };
NoRet.java:4: error: incompatible types: bad return type in lambda expression
        Function<Integer, String> noReturn = n -> { String s = "#" + n; };
                                             ^
    missing return value

void-Compatible and Value-Compatible Lambdas

An expression body that is a method call can fit both kinds of method — one that returns a value and one that returns void (the value is then simply discarded). This flexibility sometimes decides which overload is chosen:

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

public class VoidCompat {
    public static void main(String[] args) throws Exception {
        List<String> log = new ArrayList<>();
        Consumer<String> c = s -> log.add(s);
        Predicate<String> p = s -> log.add(s);
        c.accept("one");
        System.out.println(p.test("two") + " " + log);

        try (ExecutorService pool = Executors.newSingleThreadExecutor()) {
            Future<?> f1 = pool.submit(() -> System.out.println("Runnable: no result"));
            Future<Integer> f2 = pool.submit(() -> 6 * 7);
            System.out.println("f1=" + f1.get() + " f2=" + f2.get());
        }

        Object o = (Runnable) () -> System.out.println("cast gives the lambda a target type");
        ((Runnable) o).run();

        boolean descending = true;
        Comparator<Integer> order = descending ? (a, b) -> b - a : (a, b) -> a - b;
        List<Integer> nums = new ArrayList<>(List.of(3, 1, 2));
        nums.sort(order);
        System.out.println(nums);
    }
}

Output:

true [one, two]
Runnable: no result
f1=null f2=42
cast gives the lambda a target type
[3, 2, 1]
  1. The same lambda text fits two interfaces. s -> log.add(s) is a Consumer<String> (the boolean that add returns is ignored) and a Predicate<String> (the boolean is the result).
  2. Overload selection. ExecutorService.submit is overloaded for Runnable (no result) and Callable<T> (returns a result). () -> System.out.println(...) has a void body, so only Runnable fits, and the Future result is null. () -> 6 * 7 is an expression with a value — the compiler prefers Callable<Integer>, so f2.get() returns 42.
  3. A cast supplies a target type where there is none: Object o = () -> ... wouldn't compile, because Object isn't a functional interface.
  4. Conditional expressions pass the target type to both branches, so each branch can be a lambda.

(Comparators written as b - a are fine for small values like these, but can overflow for large ones; Integer.compare or Comparator.reverseOrder() are safer.)

Lambdas That Create Lambdas

A lambda is a value, so methods can return lambdas, and lambdas can return lambdas:

import java.util.function.*;

public class Returning {
    static Function<Double, Double> discount(double percent) {
        return price -> price * (100 - percent) / 100;
    }

    static Supplier<Integer> counter() {
        int[] n = {0};
        return () -> ++n[0];
    }

    public static void main(String[] args) {
        Function<Double, Double> festive = discount(20);
        Function<Double, Double> student = discount(50);
        System.out.println(festive.apply(4999.0) + " " + student.apply(4999.0));

        Function<Double, Double> both = festive.andThen(student);
        System.out.println("stacked: " + both.apply(4999.0));

        Supplier<Integer> ids = counter();
        System.out.println(ids.get() + " " + ids.get() + " " + ids.get());

        Function<Integer, Function<Integer, Integer>> adder = a -> b -> a + b;
        Function<Integer, Integer> add10 = adder.apply(10);
        System.out.println(add10.apply(5));
    }
}

Output:

3999.2 2499.5
stacked: 1999.6
1 2 3
15
  • discount(20) returns a lambda that remembers percent = 20. Each call to discount creates a separate function with its own captured value. A lambda together with the variables it captured is called a closure.
  • andThen, a default method of Function, composes two functions: 20 % off, then 50 % off the result.
  • counter() returns a supplier whose captured array keeps state between calls, so it produces 1, 2, 3. (This style is fine in single-threaded code; for shared counters use AtomicInteger.)
  • a -> b -> a + b is a lambda that returns another lambda — currying. -> groups to the right, so it reads a -> (b -> a + b). adder.apply(10) produces a function that adds 10.

Readability Guidelines

  • Keep lambdas short — ideally one expression. If a lambda grows beyond three or four lines, move the logic into a named method and use a method reference.
  • Omit parameter types unless they help the reader; add them when the type isn't obvious from the context.
  • Prefer an expression body over { return x; }.
  • Don't nest lambdas deeply; curried chains like a -> b -> c -> ... are hard to read in Java.
  • In Java 22 and later, an unused parameter can be written as _ (an unnamed variable): (_, value) -> value. In Java 21 this is a preview feature.

Practical Example: An Operator Table for a Calculator

A calculator, rule engine or command interpreter maps names to behaviour. Storing lambdas in a Map turns that mapping into data: adding an operation means adding one entry, not another branch in a long switch. This evaluator processes expressions in postfix notation (operators after their operands, as on some financial calculators: 2 3 + means 2 + 3).

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

public class Calc {
    static final MathContext MC = new MathContext(10, RoundingMode.HALF_UP);

    static final Map<String, BinaryOperator<BigDecimal>> BINARY = Map.of(
        "+", BigDecimal::add,
        "-", BigDecimal::subtract,
        "*", (a, b) -> a.multiply(b),
        "/", (a, b) -> {
            if (b.signum() == 0) throw new ArithmeticException("division by zero");
            return a.divide(b, MC);
        },
        "%", (a, b) -> a.multiply(b).divide(BigDecimal.valueOf(100), MC),
        "max", BigDecimal::max);

    static final Map<String, UnaryOperator<BigDecimal>> UNARY = Map.of(
        "neg", BigDecimal::negate,
        "round", x -> x.setScale(2, RoundingMode.HALF_UP),
        "gst18", x -> x.multiply(new BigDecimal("1.18")));

    static BigDecimal pop(Deque<BigDecimal> stack, String operator) {
        if (stack.isEmpty()) throw new IllegalArgumentException("missing operand for " + operator);
        return stack.pop();
    }

    static BigDecimal evaluate(String expression) {
        Deque<BigDecimal> stack = new ArrayDeque<>();
        for (String token : expression.trim().split("\\s+")) {
            if (BINARY.containsKey(token)) {
                BigDecimal b = pop(stack, token), a = pop(stack, token);
                stack.push(BINARY.get(token).apply(a, b));
            } else if (UNARY.containsKey(token)) {
                stack.push(UNARY.get(token).apply(pop(stack, token)));
            } else {
                stack.push(new BigDecimal(token));
            }
        }
        if (stack.size() != 1) throw new IllegalArgumentException("malformed expression: " + expression);
        return stack.pop();
    }

    public static void main(String[] args) {
        List<String> inputs = List.of(
            "2 3 + 4 *",
            "4999 10 %",
            "4999 4999 10 % - gst18 round",
            "1 3 /",
            "1200 950 max neg",
            "5 0 /",
            "1 2",
            "5 +");
        for (String in : inputs) {
            try {
                System.out.printf("%-30s = %s%n", in, evaluate(in));
            } catch (RuntimeException e) {
                System.out.printf("%-30s ! %s%n", in, e.getMessage());
            }
        }
    }
}

Output:

2 3 + 4 *                      = 20
4999 10 %                      = 499.9
4999 4999 10 % - gst18 round   = 5308.94
1 3 /                          = 0.3333333333
1200 950 max neg               = -1200
5 0 /                          ! division by zero
1 2                            ! malformed expression: 1 2
5 +                            ! missing operand for +

How it works:

  1. Two operator tables. BinaryOperator<BigDecimal> (two operands → result) and UnaryOperator<BigDecimal> (one operand → result) are functional interfaces from java.util.function. Each map entry pairs a symbol with its behaviour.
  2. Every lambda form appears: method references (BigDecimal::add) where an existing method does the job, expression lambdas ((a, b) -> a.multiply(b)), and a block lambda for division, which needs a check before the calculation.
  3. The evaluation loop pushes numbers onto a stack; an operator pops its operands, applies its lambda, and pushes the result. 2 3 + 4 * computes (2 + 3) * 4 = 20. The longer example takes 10 % of 4999 (499.9), subtracts it from 4999 (4499.1), adds 18 % GST (5308.938) and rounds to two decimals.
  4. BigDecimal with a MathContext gives exact money arithmetic; division uses 10 significant digits, because 1/3 has no exact decimal representation.
  5. Errors are reported clearly: division by zero from inside the lambda, a missing operand from pop, and leftover values from the final size check.

Adding a new operation — "sqrt", x -> x.sqrt(MC) — is a one-line change to the table. The same pattern of mapping keys to lambdas is used for command dispatchers, HTTP route tables, validation rules and pricing strategies.

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 Syntax and get answers drawn from it.

Signed-in readers only.