unkletayo
21

Java's Stream API: lazy pipelines and absent values

How stream pipelines process elements lazily, what map and flatMap do, and how Optional represents an absent value.

Adetayo Akinsanya2026-10-206 min read

  • Java
  • Core Java
  • Streams
  • Optional
  • Functional Programming

Part 21 of the series.Read How Java treats functions as values (Part 20) first if you have not.

In this article (8 sections)
  1. Pipeline structure
  2. Laziness
  3. Intermediate operations
  4. Terminal operations
  5. Primitive streams
  6. Optional
  7. Parallel streams
  8. Prediction exercise
List<String> names = List.of("alice", "bob", "charlie", "dave");
long count = 0;
for (String name : names) {
    if (name.length() > 3) {
        count++;
    }
}

This is a loop over a known collection. Suppose the names came from a database query instead, returning ten million rows. The loop would hold ten million strings in memory before processing any. A stream processes elements one at a time, pulling from the source only as the terminal operation demands them.

Pipeline structure

A stream pipeline has three parts: a source, zero or more intermediate operations, and one terminal operation.

long count = names.stream()          // source
    .filter(n -> n.length() > 3)     // intermediate
    .count();                         // terminal

The source produces elements. Each intermediate operation transforms or filters the stream, returning a new stream. The terminal operation consumes the stream and produces a result (or a side effect). The source is not touched until the terminal operation runs.

Laziness

Intermediate operations are lazy: they describe transformations but do not execute them. Only the terminal operation triggers execution.

Stream<String> pipeline = names.stream()
    .filter(n -> { System.out.println("filter: " + n); return n.length() > 3; })
    .map(n -> { System.out.println("map: " + n); return n.toUpperCase(); });

// Nothing has printed yet — the pipeline is defined but not running
long count = pipeline.count();  // execution starts here

When count() runs, elements flow through the pipeline one at a time. For each element: filter runs. If it passes, map runs on that element. Only then does the next element enter. The pipeline processes “alice”, then “bob”, then “charlie”, and so on.

This matters for short-circuiting. findFirst() stops after finding the first matching element:

Optional<String> first = names.stream()
    .filter(n -> n.length() > 4)
    .findFirst();
// stops after finding "alice" (length 5); never touches "charlie" or "dave"

Intermediate operations

filter: keeps elements matching a predicate.

.filter(n -> n.startsWith("a"))

map: transforms each element.

.map(String::toUpperCase)   // Stream<String> -> Stream<String>
.map(String::length)        // Stream<String> -> Stream<Integer>

flatMap: transforms each element into a stream and flattens the results.

List<List<String>> groups = List.of(
    List.of("alice", "bob"),
    List.of("charlie", "dave")
);

groups.stream()
    .flatMap(Collection::stream)  // Stream<List<String>> -> Stream<String>
    .forEach(System.out::println);
// alice, bob, charlie, dave

The difference between map and flatMap: map turns Stream<T> into Stream<R> by applying a function that returns R. flatMap turns Stream<T> into Stream<R> by applying a function that returns Stream<R> and merging the resulting streams. If you map to a List, you get Stream<List<R>>. If you flatMap to a stream, you get Stream<R>.

sorted: sorts elements. Without an argument, requires the element type to be Comparable. Accepts a Comparator.

.sorted(Comparator.comparingInt(String::length).thenComparing(Comparator.naturalOrder()))

distinct: removes duplicates using equals.

limit(n): keeps at most n elements.

peek: applies a consumer for side effects, then passes the element through. Useful for debugging:

.peek(n -> System.out.println("before filter: " + n))
.filter(n -> n.length() > 3)
.peek(n -> System.out.println("after filter: " + n))

Do not use peek for anything beyond debugging. Its behavior depends on the terminal operation and is not guaranteed in all cases.

Terminal operations

count: returns the number of elements as a long.

forEach: applies a consumer to each element. No return value. Order is not guaranteed in parallel streams.

collect: accumulates elements into a container. The most flexible terminal operation.

List<String> result = names.stream()
    .filter(n -> n.length() > 3)
    .collect(Collectors.toList());

Common collectors: toList(), toSet(), toUnmodifiableList(), joining(delimiter) for strings, groupingBy(classifier) for maps, counting(), summingInt(mapper).

findFirst / findAny: returns an Optional<T>. findFirst returns the first element in encounter order. findAny may return any element (useful in parallel streams where order doesn’t matter).

anyMatch / allMatch / noneMatch: short-circuiting predicates that return boolean.

reduce: combines all elements into one.

int sum = IntStream.rangeClosed(1, 10).reduce(0, Integer::sum);  // 55

toArray: materializes the stream into an array.

Primitive streams

Autoboxing int values into Integer for every element in a large stream is expensive. Java provides IntStream, LongStream, and DoubleStream for primitive elements.

int[] numbers = {1, 2, 3, 4, 5};
int sum = Arrays.stream(numbers).sum();  // IntStream, no boxing

You can convert between object streams and primitive streams: stream.mapToInt(String::length) returns an IntStream; intStream.boxed() returns a Stream<Integer>.

Optional

Optional<T> is a container that holds either a value or nothing. It is designed for methods that may or may not return a result.

Optional<String> maybeFirst = names.stream()
    .filter(n -> n.startsWith("z"))
    .findFirst();

// Check whether a value is present
if (maybeFirst.isPresent()) {
    System.out.println(maybeFirst.get());
}

// Or use orElse
String name = maybeFirst.orElse("not found");

// Or transform if present
int length = maybeFirst.map(String::length).orElse(0);

// Or throw if absent
String required = maybeFirst.orElseThrow(() -> new IllegalStateException("expected a name"));

Optional makes “this might be absent” visible in the type. A method that returns String could return null; a method that returns Optional<String> signals that absence is a possibility the caller should handle. The caller cannot accidentally dereference an Optional without first dealing with the absent case.

Do not use Optional.get() without first calling isPresent(). It throws NoSuchElementException when the value is absent, defeating the purpose. Prefer orElse, orElseGet, map, or orElseThrow.

Optional is intended for return types, not for fields or parameters. A field of type Optional<T> can be null itself (an Optional that is null, rather than empty), which is confusing. A parameter of type Optional<T> forces the caller to wrap values in an Optional before calling, which is inconvenient. For optional fields, use a nullable field or a default value. For optional parameters, use overloading.

Parallel streams

.parallel() or Collection.parallelStream() changes the stream to run on the common fork-join pool. The pool size defaults to one less than the number of available processors.

long count = names.parallelStream()
    .filter(n -> expensiveCheck(n))
    .count();

Parallel streams are worth considering when the work per element is expensive and the collection is large. For small collections or cheap operations, the overhead of splitting and merging work is greater than the savings.

Parallel streams do not help when: the operations have side effects on shared state; the operations are inherently ordered and cannot be split; forEach is used in an order-dependent way. Stateful lambdas (capturing and modifying shared variables) in parallel streams produce data races.

Prediction exercise

List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6, 7, 8);
int result = numbers.stream()
    .filter(n -> n % 2 == 0)
    .mapToInt(n -> n * n)
    .sum();
System.out.println(result);

Trace through the pipeline: which elements pass the filter, what does mapToInt produce for each, and what does sum return? Then: could you replace mapToInt(n -> n * n).sum() with map(n -> n * n).reduce(0, Integer::sum) and get the same result? The next article covers I/O: how Java reads and writes bytes and characters, what streams and buffers do, and how to process a file without loading it all into memory at once. I/O: bytes, characters, and files continues from here.

Questions or corrections

Found a mistake or have a question about this breakdown? Reach out directly.

Reply on X (@unkletayor)Email feedback