Java Materials
← Core Java · Chapter 7

Functional programming, streams and Optional

Functional interfaces let a caller pass behavior. Predicate tests, Function transforms, Consumer performs an action and Supplier provides a value. UnaryOperator and BinaryOperator keep types aligned; primitive specializations avoid unnecessary boxing. Lambdas may capture final or effectively final locals and method references bind to a target functional signature.

Lazy pipelines and fused traversal

Definition:

A lazy stream pipeline runs as a terminal operation traverses its source.

Explanation:

Most stateless intermediate steps can process one element through the pipeline without materializing whole intermediate collections. sorted and some distinct or ordered parallel operations require state.

Illustration image:

Lazy pipelines and fused traversal. x, pear, plum · filter starts with p · map to length · findFirst gives 4Lazy pipelines and fused traversalSource or actorx, pear, plumFirst boundaryfilter starts with pInspected statemap to lengthObservable effectfindFirst gives 4
x, pear, plum · filter starts with p · map to length · findFirst gives 4

Example:

Worked Java example · see surrounding context in notes
var first = java.util.stream.Stream.of("x","pear","plum")
    .filter(s -> s.startsWith("p"))
    .map(String::length).findFirst();
System.out.println(first.orElse(0));

Expected behavior. The first retained value has length 4; finding it does not require processing all later elements.

Internal working:

Do not depend on side effects in map or peek, which can be skipped by optimizations or early termination.

Interview questions:

Why is peek unsuitable for required side effects?

Short-circuiting or optimization can omit traversal of elements; stream side effects are not a business execution guarantee.

Collectors, reduction and parallel splits

Definition:

A collector defines how to accumulate, combine and finish a reduction.

Explanation:

A parallel reduction can regroup operations, so use an associative accumulator and neutral identity.

Illustration image:

Collectors, reduction and parallel splits. Input split · Local result A · Local result B · Associative combinerCollectors, reduction and parallel splitsSource or actorInput splitFirst boundaryLocal result AInspected stateLocal result BObservable effectAssociative combiner
Input split · Local result A · Local result B · Associative combiner

Example:

Worked Java example · see surrounding context in notes
long total = java.util.stream.LongStream.rangeClosed(1,1000).parallel()
    .reduce(0L, Long::sum);
System.out.println(total);

Expected behavior. 500500. Using a nonzero identity would add that number to one or more partitions.

Internal working:

A Collector describes supplier, accumulator, combiner and finisher; mutable accumulators can be kept separate during normal parallel reduction. With concurrent collectors, consider ordering requirements and synchronization of the downstream data structure.

Interview questions:

Why does a parallel sum need a neutral identity?

Each partial reduction can start independently; a nonneutral seed can be counted multiple times.

Optional and boundary decisions

Definition:

Optional models a possible value and provides explicit transformations and fallbacks.

Explanation:

Optional is useful for representing an absent result.

Illustration image:

Optional and boundary decisions. Input present · map transforms value · Result present · Supplier not calledOptional and boundary decisionsSource or actorInput presentFirst boundarymap transforms valueInspected stateResult presentObservable effectSupplier not called
Input present · map transforms value · Result present · Supplier not called

Example:

Worked Java example · see surrounding context in notes
var token = java.util.Optional.of("paid");
String status = token.map(String::toUpperCase)
    .orElseGet(() -> "UNKNOWN");
System.out.println(status);

Expected behavior. Prints PAID and does not evaluate the fallback supplier.

Internal working:

Do not hide a real failure by converting all exceptions to empty. orElse evaluates its argument before the call, while orElseGet calls the supplier only for absence. flatMap handles a function already returning Optional. Prefer primitive optionals for primitive aggregates when boxing matters.

Interview questions:

Which fallback is evaluated even when a value exists?

orElse evaluates its argument before the method call; orElseGet invokes its supplier only for an empty Optional.

Reference subtopics

Composition and laziness

compose applies the supplied function before this one; andThen applies it after. Predicate.and and or short-circuit. Stream intermediates run when a terminal operation drives traversal, and a stream is single-use. map maps one element to one result; flatMap flattens nested streams; mapMulti, available from 16, can emit multiple results without creating one stream per input.

Pipeline operations and reductions

filter tests, distinct de-duplicates, sorted imposes order, and skip or limit slice an encounter-ordered stream. Use reduce with an associative operation and neutral identity; use collect for mutable accumulation with independent partial containers and a combiner. Primitive streams provide specialized numeric terminals.

Collector recipes

groupingBy uses a classifier, partitioningBy a Boolean predicate and counting yields Long. Add mapping or flatMapping (from 9) as downstream adapters. toMap needs a merge rule for valid duplicates. collectingAndThen applies a finishing step, joining assembles strings and summarizingInt supplies count, sum, min, max and average.

Optional and parallelism

map wraps non-null output and flatMap composes Optional results. orElse evaluates eagerly; orElseGet builds a fallback lazily; orElseThrow makes absence explicit. A Spliterator describes how a source traverses or splits. Parallel streams pay split and coordination overhead; ordered or blocking work can bottleneck. Benchmark and keep effects outside stream internals.

Run the complete Java labs ↗ · Java reference ↗