Java Lambda Syntax
The Parts of a Lambda
Every lambda expression has three parts:
(parameters) -> body
| Part | Meaning |
|---|---|
| Parameter list | The inputs, matching the parameters of the functional interface's single abstract method |
Arrow -> | Separates the parameters from the body |
| Body | Either 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
| Form | Example | Notes |
|---|---|---|
| No parameters | () -> "Vanakkam" | Empty parentheses are required |
| One parameter, no type | s -> s.length() | Parentheses are optional for exactly one untyped parameter |
| One parameter in parentheses | (s) -> s.length() | Same meaning |
| Several parameters | (a, b) -> a + b | Parentheses required |
| Explicit types | (Integer a, Integer b) -> a + b | Rarely needed; useful when inference fails or for clarity |
var (Java 11+) | (var a, var b) -> a + b | Inferred 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 noreturnkeyword and no semicolon inside. - Block body:
{ statements }. Use it for several statements. If the interface method returns a value, every path must end inreturn value;— as ingrade. If it returnsvoid,return;is optional. - Empty block:
() -> { }is a validRunnablethat 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]
- The same lambda text fits two interfaces.
s -> log.add(s)is aConsumer<String>(thebooleanthataddreturns is ignored) and aPredicate<String>(thebooleanis the result). - Overload selection.
ExecutorService.submitis overloaded forRunnable(no result) andCallable<T>(returns a result).() -> System.out.println(...)has avoidbody, so onlyRunnablefits, and theFutureresult isnull.() -> 6 * 7is an expression with a value — the compiler prefersCallable<Integer>, sof2.get()returns 42. - A cast supplies a target type where there is none:
Object o = () -> ...wouldn't compile, becauseObjectisn't a functional interface. - 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 rememberspercent = 20. Each call todiscountcreates a separate function with its own captured value. A lambda together with the variables it captured is called a closure.andThen, a default method ofFunction, 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 useAtomicInteger.)a -> b -> a + bis a lambda that returns another lambda — currying.->groups to the right, so it readsa -> (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:
- Two operator tables.
BinaryOperator<BigDecimal>(two operands → result) andUnaryOperator<BigDecimal>(one operand → result) are functional interfaces fromjava.util.function. Each map entry pairs a symbol with its behaviour. - 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. - 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. BigDecimalwith aMathContextgives exact money arithmetic; division uses 10 significant digits, because1/3has no exact decimal representation.- 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.