Skip to content

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.

Beginner 16 min read·Lesson 35 of 39 in Java Programming

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

Java
Runnable r = () -> System.out.println("run");
Predicate<String> blank = s -> s.isBlank();
Function<String, Integer> len = String::length; // method reference
BinaryOperator<Integer> add = (a, b) -> a + b;
Comparator<String> byLength = Comparator.comparingInt(String::length);
Supplier<List<String>> make = ArrayList::new; // constructor reference
  • A lambda's parameter names must not clash with local variables.
  • this inside 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

Java
import java.util.function.*;
public class Main {
public static void main(String[] args) {
Predicate<Integer> isEven = n -> n % 2 == 0;
Function<String, Integer> length = s -> s.length();
Consumer<String> shout = s -> System.out.println(s.toUpperCase() + "!");
Supplier<String> greeting = () -> "Hello";
BinaryOperator<Integer> max = (a, b) -> a >= b ? a : b;
UnaryOperator<String> twice = s -> s + s;
System.out.println(isEven.test(10) + " " + isEven.test(7));
System.out.println(length.apply("lambda"));
shout.accept("java");
System.out.println(greeting.get() + " " + max.apply(4, 9) + " " + twice.apply("ab"));
}
}
Output
true false
6
JAVA!
Hello 9 abab

Method references and composition

Java
import java.util.*;
import java.util.function.*;
public class Main {
public static void main(String[] args) {
List<String> words = new ArrayList<>(List.of("kiwi", "", "Banana", " ", "apple"));
words.removeIf(String::isBlank); // unbound instance method
words.replaceAll(String::toLowerCase);
words.sort(Comparator.naturalOrder());
words.forEach(System.out::println); // bound instance method
Predicate<String> longWord = s -> s.length() > 4;
Predicate<String> startsWithA = s -> s.startsWith("a");
System.out.println(longWord.and(startsWithA).test("apple") + " " + longWord.negate().test("kiwi"));
Function<Integer, Integer> plus2 = x -> x + 2, times3 = x -> x * 3;
System.out.println(plus2.andThen(times3).apply(4) + " " + plus2.compose(times3).apply(4));
Function<String, Integer> parse = Integer::parseInt; // static method
System.out.println(parse.apply("41") + 1);
}
}
Output
apple
banana
kiwi
true true
18 14
42

More examples

Passing behaviour into your own methods

Java
import java.util.*;
import java.util.function.*;
public class Main {
record Order(String id, String customer, double amount, boolean paid) { }
static <T> List<T> filter(List<T> items, Predicate<? super T> keep) {
List<T> out = new ArrayList<>();
for (T item : items) if (keep.test(item)) out.add(item);
return out;
}
static <T, R> List<R> map(List<T> items, Function<? super T, ? extends R> f) {
List<R> out = new ArrayList<>();
for (T item : items) out.add(f.apply(item));
return out;
}
static void retry(int times, Supplier<Boolean> action, Consumer<String> log) {
for (int attempt = 1; attempt <= times; attempt++) {
if (action.get()) { log.accept("succeeded on attempt " + attempt); return; }
log.accept("attempt " + attempt + " failed");
}
}
public static void main(String[] args) {
List<Order> orders = List.of(new Order("A1", "Asha", 1200, true), new Order("A2", "Ravi", 450, false), new Order("A3", "Asha", 3100, false));
List<Order> unpaid = filter(orders, o -> !o.paid());
System.out.println(map(unpaid, Order::id));
double threshold = 1000; // effectively final, so the lambda may capture it
System.out.println(map(filter(orders, o -> o.amount() > threshold), o -> o.customer() + ":" + o.amount()));
int[] calls = {0}; // an array element can be changed from a lambda
retry(5, () -> ++calls[0] == 3, msg -> System.out.println(" " + msg));
Map<String, BinaryOperator<Double>> ops = Map.of("+", Double::sum, "max", Math::max);
System.out.println(ops.get("+").apply(2.5, 4.0) + " " + ops.get("max").apply(2.5, 4.0));
}
}
Output
[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

  • filter and map are generic methods that accept behaviour as Predicate and Function parameters — exactly what Streams do internally.
  • o -> !o.paid() and Order::id are passed as values; the methods decide when to call them.
  • threshold is never reassigned, so it is effectively final and can be captured by the lambda.
  • retry takes 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:

TextOutput
[A2, A3]
[Asha:1200.0, Asha:3100.0]
attempt 1 failed
attempt 2 failed
succeeded on attempt 3
6.5 4.0

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

int count = 0;
list.forEach(x -> count++); // compile error

Prefer

int count = list.size();
// or: long count = list.stream().filter(...).count();

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

names.forEach(n -> System.out.println(n));

Prefer

names.forEach(System.out::println);

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

  1. 1
    Write static <T> int countIf(List<T> list, Predicate<T> p) and use it with three different lambdas.
  2. 2
    Build 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);`
Practise this topic