On this page
  1. Lambdas, Streams & Functional Interfaces
  2. Overview
  3. Core Functional Interfaces (java.util.function)
  4. Method References
  5. Effectively Final Capture
  6. Stream Pipeline Rules

Lambdas, Streams & Functional Interfaces

Prev: Exceptions & Resource Management | Up: Language & OOP | Next: JVM & OpenJDK
Rel: java.util.stream, interface, var, Stream Pipelines & File Processing Tutorial
Ref: Java 21 API — java.util.function , Dev.java — Lambda Expressions
Tags: #public #java #functional #streams #tier/core


Overview

Java supports functional-style programming through functional interfaces (interfaces with a single abstract method), lambda expressions, method references, and the lazy java.util.stream pipeline API. Under the hood, lambdas compile to invokedynamic bytecode instructions rather than generating anonymous inner .class files.

Core Functional Interfaces (java.util.function)

Interface Signature Typical Use
Predicate<T> T -> boolean Stream.filter, Collection.removeIf
Function<T, R> T -> R Stream.map, Map.computeIfAbsent
Consumer<T> T -> void Iterable.forEach, Optional.ifPresent
Supplier<T> () -> T Lazy initialization, Optional.orElseGet
UnaryOperator<T> T -> T List.replaceAll, transformations of same type
BiFunction<T, U, R> (T, U) -> R Map.merge, two-input reductions

Primitive specializations (IntPredicate, ToLongFunction<T>, IntBinaryOperator) avoid autoboxing overhead in tight numeric pipelines.

Method References

Prefer method references over trivial lambdas when they improve readability:

Effectively Final Capture

Lambdas can capture local variables only if they are final or effectively final (never reassigned after initialization). If you need accumulation, prefer stream reductions (collect, reduce, sum) over mutating external state.

Stream Pipeline Rules

  1. Lazy evaluation: Intermediate operations (filter, map, flatMap, sorted) do no work until a terminal operation (toList, collect, reduce, count, findFirst) runs.
  2. Single-use: A Stream cannot be reused after its terminal operation executes.
  3. Avoid side effects: Do not mutate shared collections inside map/filter lambdas; use Collectors instead.
  4. Parallel streams with care: parallelStream() uses the shared ForkJoinPool.commonPool(). Reserve it for CPU-bound, large, easily splittable data sets (ArrayList, arrays)—never for blocking I/O (use virtual threads instead).
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

record Sale(String region, int cents) {}

static Map<String, Integer> totalsByRegion(List<Sale> sales) {
    return sales.stream()
        .filter(s -> s.cents() > 0)
        .collect(Collectors.groupingBy(
            Sale::region,
            Collectors.summingInt(Sale::cents)
        ));
}

Linked from

Related notes