Module 10 · Lambdas, Streams, Concurrency and JDBC — topic 1 of 5
Lambda Expressions and Method References
Writing behaviour as values with lambdas, the built-in functional interfaces (Predicate, Function, Consumer, Supplier, BiFunction), method references and effectively final captures.
Learning objectives
- Write lambdas with zero, one and several parameters
- Use Predicate, Function, Consumer, Supplier and their compositions
- Replace simple lambdas with method references
Definition
A lambda expression is a concise anonymous function — parameters, an arrow and a body — that implements a functional interface (an interface with a single abstract method). A method reference such as String::length is a shorthand for a lambda that just calls an existing method.
Introduction
Often you want to pass *behaviour* to a method: how to sort, what to filter, what to do with each element. Before Java 8 that meant writing an anonymous class with lots of boilerplate. A lambda says the same thing in one line: list.removeIf(s -> s.isBlank()).
Why it matters
Lambdas power the Streams API, Comparator chains, event handlers, and modern libraries such as CompletableFuture and Spring.
Code that passes behaviour as values is shorter and easier to customise.
Detailed explanation
Syntax. (parameters) -> expression or (parameters) -> { statements; }. Parameter types are usually inferred: x -> x * x, (a, b) -> a + b, () -> System.out.println("hi"). A block body needs an explicit return for a value.
Functional interfaces. A lambda has no type of its own; it implements whatever functional interface the context expects — Runnable, Comparator, or one of the general interfaces in java.util.function.
The core interfaces. Predicate<T> (T → boolean, e.g. filters), Function<T, R> (T → R, e.g. transformations), Consumer<T> (T → nothing, e.g. printing), Supplier<T> (nothing → T, e.g. factories), BiFunction<T, U, R>, UnaryOperator<T> and BinaryOperator<T>. Primitive versions such as IntPredicate avoid boxing.
Composition. Predicate.and/or/negate, Function.andThen/compose and Comparator.thenComparing build new behaviour from existing pieces.
Method references. Four forms: static (Integer::parseInt), bound instance (System.out::println), unbound instance (String::toUpperCase — the object is the first argument) and constructor (ArrayList::new). Use them when a lambda only forwards its arguments.
Captured variables. A lambda can use local variables from the enclosing scope only if they are *effectively final* — assigned once and never changed. This avoids confusing behaviour, especially across threads. Fields and array elements can still be modified.
Syntax
- A lambda's parameter names must not clash with local variables.
thisinside a lambda refers to the enclosing object (unlike in an anonymous class).- Mark your own single-method interfaces with @FunctionalInterface.
Code examples
Lambdas with the core functional interfaces
true false 6 JAVA! Hello 9 abab
Method references and composition
apple banana kiwi true true 18 14 42
More examples
Passing behaviour into your own methods
[A2, A3] [Asha:1200.0, Asha:3100.0] attempt 1 failed attempt 2 failed succeeded on attempt 3 6.5 4.0
Step-by-step explanation
filterandmapare generic methods that accept behaviour as Predicate and Function parameters — exactly what Streams do internally.o -> !o.paid()andOrder::idare passed as values; the methods decide when to call them.thresholdis never reassigned, so it is effectively final and can be captured by the lambda.retrytakes a Supplier (the action) and a Consumer (the logger); the action succeeds on the third call because the counter is an array element, which lambdas may modify.- A map from names to
BinaryOperators turns strings into behaviour — the basis of simple calculators and command dispatchers.
Expected output
Running “Passing behaviour into your own methods” prints exactly:
Practical applications
- Sorting and filtering with Comparator and Predicate
- Event listeners and callbacks in GUI and web frameworks
- Retry, timing and logging wrappers
- Strategy objects chosen at run time
Best practices
- Keep lambdas short; move longer logic into a named method and use a method reference.
- Prefer the standard java.util.function interfaces over defining your own.
- Use primitive specialisations (IntPredicate, ToIntFunction) in hot code to avoid boxing.
Common mistakes
Modifying a captured local variable
Avoid
Prefer
Local variables used in lambdas must be effectively final; use the result of a method or stream operation instead.
Writing a lambda that only forwards
Avoid
Prefer
A method reference is shorter and states the intent directly.
Important notes
- Lambdas were added in Java 8, together with java.util.function and the Streams API.
- Checked exceptions can't be thrown from the standard functional interfaces; wrap them or define your own interface.
Key takeaways
- A lambda implements a functional interface: one abstract method.
- Predicate tests, Function transforms, Consumer consumes, Supplier supplies.
- Method references (Class::method) shorten lambdas that only call a method; captured locals must be effectively final.
Try it yourself
- 1Write
static <T> int countIf(List<T> list, Predicate<T> p)and use it with three different lambdas. - 2Build a calculator that maps "+", "-", "*" and "/" to IntBinaryOperator lambdas.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
4 questions test this exact topic. Answers and explanations are revealed after you submit.
- BeginnerWhat is printed?
- ModerateWhat is printed?
- ModerateWhy doesn't this compile? `int total = 0; list.forEach(x -> total += x);`