mattone
dopo mattoneTHE BOOK SERIES
IT/EN
← Java guide

Java 25 · 18/39

18. Stream API: Pipelines, Reductions and Gatherers

Java 25 · Complete guide · Draft under review

Read the editorial note for the review status.

Search the whole guide →

From the Collection to the Calculation

Let us return to the list model from Chapter 17 and consider the numbers 1, 2, 3, 4, 5, 6, 3. Now we want a new list without values equal to 3. We can write a loop, check every number and add allowed ones to a new list. The Stream API offers another form for describing that calculation: data.stream().filter(number -> number != 3).toList(). filter expresses the condition, and toList produces the result. The loop remains a valid solution; the stream is useful when the transformation sequence makes intention easier to read.

A stream does not require the reader to start from concepts such as monads and does not, on its own, promise asynchronous work or greater speed. A Java stream is a processing view over a source of elements, with aggregate operations that can be composed. It is not, in itself, a structure containing elements like a list; it is not automatically asynchronous; a sequential pipeline normally works in the calling thread. Parallelism is a separate choice, with its own costs and constraints.

Definition – Pipeline. A pipeline comprises a source, zero or more intermediate operations and a terminal operation. The source can be a collection, an array, a generator or a resource such as a file. Intermediate operations describe transformations; the terminal requests a result or an effect and consumes the stream. After consumption, the same stream cannot be reused.

In the complete program, data.stream() creates a stream from the list, filter describes the elements to retain and toList() produces [1, 2, 4, 5, 6]. The second print still shows [1, 2, 3, 4, 5, 6, 3]: the pipeline has not modified the source list. Stream.toList() returns an unmodifiable list. If we want a new modifiable ArrayList, we will explicitly construct it from the result or use an appropriate collector.

Figure 18.1 shows the logical order of steps. It should not be read as a promise that every step is completed on all elements before the next starts: the implementation can traverse the pipeline element by element and, when legal, avoid unnecessary work.

Source, operations and result of a stream
Figure 18.1 – The source feeds filter, and the terminal toList materializes a new list. The stream describes processing; the final list is an object distinct from the source.

From the Loop to the Pipeline, Without Losing Control

Let us return to the problem opening the chapter: eliminating from the new list all values equal to 3. In the following for loop, we can see three operations: traversing the source, deciding whether an element passes, and adding it to the result. The pipeline filter(...).toList() retains the same three responsibilities, but entrusts traversal to the API. Iteration still takes place: our code describes the condition and shape of the result while the library manages the path. We therefore compare both results on the same data before choosing the more readable form. A stream is useful when calculation reads as a sequence of transformations; if each element requires many error branches with different effects, an explicit loop may make the work easier to follow and check.

List<Integer> source = List.of(1, 2, 3, 4, 5, 6, 3);
List<Integer> copy = new ArrayList<>();
for (int value : source) {
    if (value != 3) copy.add(value);
}
List<Integer> filtered = source.stream()
        .filter(value -> value != 3)
        .toList();

The two results have the same elements [1, 2, 4, 5, 6], but not the same modifiability contract: copy is an ArrayList we can modify, while the list returned by Stream.toList() is unmodifiable. The source source remains [1, 2, 3, 4, 5, 6, 3] in both cases. This verification prevents confusing similar output with completely identical behavior. If the result must be a mutable list, we declare and construct it; if it must not change, the list from toList makes that constraint useful.

A third version with source.forEach(x -> { if (...) copy.add(x); }) uses a lambda but retains the external accumulator. On a small sequential loop it can work; it does not offer the advantage of a result expressed by the pipeline and becomes dangerous if someone replaces the source with a parallel stream. The presence of a lambda is not enough to make code “functional”. It is the relationship between input, transformations and effects that establishes whether the model is suitable.

Source, Intermediate Steps, Terminal

A pipeline begins with a source. source.stream() produces a stream associated with the list. filter is an intermediate operation: it defines which elements can continue and returns another stream. toList is terminal: it requests processing and returns a list. count, sum, findFirst, anyMatch, collect and forEach are also terminals, but do not all produce the same result type. Some return a value, some an Optional, some an effect. Before choosing the terminal, we formulate the question: do we want all elements, the first, a count, a sum or a print?

The distinction is not a graphical convention. A chain ending with filter has only described work; if unconsumed, it does not produce the filtered list. A chain calling count has consumed the stream: the same object cannot be traversed again with toList. We can instead ask the source list for a new stream() for a second question. This characteristic resembles an Iterator that, once advanced to the end, does not automatically return to the beginning. We must not confuse consumption of the pipeline with automatic closure of an external resource: a file stream still requires file management.

Box – Laziness Is Not a Promise of Calls. The API guarantees the pipeline result according to the operation contracts, rather than that an intermediate lambda is invoked exactly once for every element in every case. An implementation can avoid unnecessary work. This is why map(x -> { record(x); return x; }).count() is the wrong place for a necessary action such as record. If the action must happen, we make it explicit and control its lifecycle; if we only want to count, we use count without a hidden effect.

Building Streams from Different Sources

The List is the most familiar source, but a stream can come from an array, values declared in code, a generator or a file. Stream.of("red", "blue") is practical for a few known values; Stream.<String>empty() represents no elements. Stream.ofNullable(value) produces zero elements when the value is null and one when present. It should not be confused with Stream.of(value): with a single null reference, the overload and intended meaning can be ambiguous to the reader; choosing ofNullable makes absence explicit.

Stream.builder() allows values to be added one at a time before constructing the stream. It is useful when elements are selected during a short preparation; after build, the builder is not a container to continue modifying. For data already in a collection, creating a builder and copying every value adds work without benefit. Arrays.stream(array) uses an existing array; with int[] it produces IntStream, and with String[] it produces Stream<String>. The same method name hides overloads suitable for different types, so we always read the return type chosen by the compiler.

Comma-separated text can be read with Pattern.compile(",").splitAsStream(text). Here the separator is a regular expression. A simple comma requires no escape, but a dot would mean “any character” if unprotected. After splitting we can apply map(String::strip) and filter(s -> !s.isEmpty()) to clean elements. A pipeline does not automatically validate contents: if an entry is malformed, a domain rule and error decision are needed.

Stream.generate(supplier) requests new elements from the supplier whenever needed. Without a limit it can produce an endless sequence. Stream.iterate(seed, step) constructs the first value from the seed and subsequent values by applying the step to the previous one. The predicate form Stream.iterate(seed, continueWhile, step) stops the sequence when the condition is no longer true. In the complete program StreamCatalogDemo.java, Stream.iterate(2, n -> n <= 8, n -> n + 2).toList() produces [2, 4, 6, 8]: the value 2 is the seed, n <= 8 decides whether to emit it, and n + 2 prepares the next. The order of the three arguments is not arbitrary; it follows “where do I start, when do I continue, how do I advance?”.

An infinite source requires a terminal that can stop or an intermediate operation making it finite. Stream.generate(() -> "x").limit(3).toList() terminates with three values; Stream.generate(() -> "x").toList() has no natural end and can exhaust resources. findFirst() can terminate even without limit, provided the search can find an element and previous operations let it pass. The presence of a short-circuit operation does not by itself guarantee that every pipeline finishes: if the predicate is never satisfied, the search can continue endlessly.

Evaluation Is Lazy

Many intermediate operations are lazy: constructing data.stream().filter(...) does not immediately traverse all the data. Required work happens when a terminal such as toList, count, findFirst or forEach consumes the pipeline. This allows short-circuit operations not to necessarily examine the entire source. For example, on an ordered stream, filter(...).findFirst() can stop as soon as it finds the first suitable element.

Figure 18.2 separates the moment we prepare the pipeline from the moment we request the result. Anna's case is deliberately minimal: it allows us to verify why Andrea and Luca do not necessarily need to be examined.

Preparation and lazy consumption of a pipeline
Figure 18.2 – Constructing filter does not visit names; findFirst starts the search and can stop it at the first result.

Laziness does not authorize hiding effects in filter or map expecting them to always execute once per element. Some pipelines can avoid or reorganize calls when doing so does not change the result required by the terminal. A predicate should describe a condition, rather than record an invoice or increment a counter necessary for program correctness. The Java 25 documentation for package java.util.stream calls behaviors that do not modify the source during processing non-interfering, and those not depending on state varying between elements stateless.

A Stream object is used for a single pipeline consumed once. If we need to perform two calculations on the same collection, we can create two streams from the collection: data.stream() at every calculation. Retaining the stream reference and calling two terminals on it is a lifecycle error. The exception that may appear is a consequence, rather than the principle to memorize.

Observing Laziness at Execution

Let us verify the distinction just introduced without an artificial pause. We prepare a list of three names and a filter printing a diagnostic line when called. Immediately after constructing the pipeline, we print prepared; then invoke findFirst. Output begins with prepared, because simply constructing the pipeline does not traverse the list. Only the terminal sets work in motion. If the first name satisfies the predicate, the search can stop there. Printing in the predicate is a temporary tool for observing execution, rather than part of application logic.

List<String> names = List.of("Anna", "Andrea", "Luca");
Stream<String> search = names.stream().filter(name -> {
    System.out.println("Examining " + name);
    return name.startsWith("A");
});
System.out.println("Pipeline prepared");
String first = search.findFirst().orElse("none");
System.out.println("Found " + first);

With this data order, we expect Pipeline prepared first, then Examining Anna, and finally Found Anna. The program allows us to associate the problem “find the first suitable name” with the solution filter plus findFirst, the verification of short-circuiting and the transfer to a larger list. If we replace findFirst with toList, the terminal must produce all passing names and therefore also traverses subsequent elements. If we insert sorted() before findFirst, sorting may need to know all elements before returning the first sorted one. The presence of a short terminal does not erase the cost of earlier operations.

Operation order must be reasoned through carefully. Filtering before an expensive transformation can save work, if the filter already has the necessary information and the two operations can be moved without changing meaning. If the filter must evaluate the transformation's result, then transformation must come first. distinct and sorted can also change which elements a limit sees: moving limit(10) before sorted means sorting only the first ten encountered elements, rather than choosing the ten smallest in the whole source. Performance rules are not permission to silently change the answer to the problem.

A Fresh Stream for Every Question

A list of cities can first answer “how many are there?” and then “which comes first alphabetically?”. These are two terminals and require two streams. The simplest form is to call cities.stream() twice. If constructing the source is encapsulated in a method, we can use Supplier<Stream<City>> and call get() to obtain a new pipeline for each question. The supplier does not necessarily regenerate the data: it can return a new stream over the same list. If instead it opens a file at every call, it also carries closure responsibility and an I/O cost that must not be hidden.

Supplier<Stream<String>> source = () -> names.stream();
long howMany = source.get().count();
String first = source.get().sorted().findFirst().orElse("none");

This solution is useful when several functions receive the ability to create a new stream; in ordinary code, two direct calls to names.stream() remain more immediate. A pipeline is not a collection to retain for reuse. The error message stream has already been operated upon or closed reports that we tried to traverse a consumed object again; recreating the stream from the source is the answer, provided the source is still available and valid.

Transforming, Flattening and Stopping

map transforms every element into another value. From titles we can obtain lengths with map(String::length). If transformation of an element in turn produces several elements, flatMap allows them to be flattened into a single stream. In the program, the lines "Java,Nets" and "API" become [Java, Nets, API] through flatMap(line -> Stream.of(line.split(","))). Transformation is visible: first we split every line, then combine the resulting small streams.

mapMulti is another form for producing zero or more results from an element through a consumer supplied to the function. It can be useful when opening many small streams in flatMap would make the pipeline less suited to the problem, but the choice must be made after verifying that the body remains readable. Stream.ofNullable(x) produces zero elements if x is null, and one otherwise; it is useful to avoid a separate check in small adaptations, without turning null into an always desirable modeling choice.

On a source with encounter order, takeWhile retains the prefix while the predicate is true and stops at the first element making it false. dropWhile discards that prefix and leaves the rest. They are not synonyms for filter, which also evaluates the condition on later elements. Stream.iterate(seed, predicate, step) can generate a finite sequence when the predicate establishes when to stop; if a limit is missing, a terminal requiring all elements may not terminate. limit and skip are other cutting tools, but their cost depends on order and source.

Primitive streams such as IntStream, LongStream and DoubleStream avoid boxing every element and offer numerical operations such as sum and average. It is not always useful to transform everything into primitives: if elements have domain meaning, losing the object type can make code less clear. The right choice brings together contract, readability and measurement when performance really matters.

Intermediate Operations: Following One Element at a Time

filter retains or discards an element according to a Predicate. On ["Rome", "Rovigo", "Bari"], the filter city -> city.startsWith("R") produces the first two cities. map applies a Function to every arriving element: map(String::toUpperCase) changes text, while map(String::length) also changes the stream type from Stream<String> to Stream<Integer>. If we want to sum lengths, mapToInt(String::length).sum() directly expresses a numerical calculation without an intermediate wrapper list.

distinct eliminates duplicates according to the elements' notion of equality. For strings, distinction is case-sensitive: "Rome" and "ROME" are not equal. If we want distinct cities independently of spelling, we must decide how to normalize them, and map(String::toUpperCase).distinct() is a possible solution. But normalizing before retaining the original name also means losing the initial spelling. This is a modeling problem, rather than a hidden parameter of distinct.

sorted sorts pipeline elements. For strings it uses natural order, which may not coincide with local linguistic sorting; for domain objects a Comparator or a natural order defined by the class is needed. sorted(Comparator.comparing(Book::title)) says which property guides comparison. Because sorting requires knowing the elements to compare, sorted may require retaining much data. On a potentially infinite source, sorted().findFirst() is not a harmless trick for finding the minimum: a reduction min(comparator) expresses the request better and can work without sorting every element.

skip(n) drops the first n elements, and limit(n) lets no more than n pass. On an ordered source they are useful for a position window, but do not automatically represent stable pagination of data that keeps changing. takeWhile and dropWhile instead operate on a prefix defined by a predicate: after the first element interrupting the prefix, they do not resume as a general filter would.

flatMap comes into play when an element of the source in turn produces a sequence. A list of lines "Java,Nets", "API" becomes a list of words: map(line -> line.split(",")) would give a stream of arrays, rather than a single flow of words yet; flatMap(line -> Arrays.stream(line.split(","))) combines the elements of small streams into one flow. The word “flatten” indicates precisely the move from a nested level to a linear one. mapMulti permits zero or more elements to be emitted without explicitly constructing a stream for every input; it is useful mainly when this choice simplifies a concrete case, rather than to replace every flatMap in advance.

Stateless intermediate operations, such as ordinary filter and map with stateless functions, do not need to remember previous elements. Stateful operations such as distinct and sorted instead need information about the set already seen or the set to sort. This explains a cost difference that a list of method names does not show. A pipeline can be lazy and yet need to accumulate many elements when the terminal arrives. Laziness concerns when work occurs; necessary memory also depends on which operation we requested.

Terminals Answer Different Questions

If we ask “how many cities begin with R?”, filter(...).count() produces a long. If we ask “does at least one exist?”, anyMatch(...) produces a boolean and can stop at the first success. allMatch asks whether all satisfy the condition; noneMatch whether none do. On an empty stream, anyMatch is false, while allMatch and noneMatch are true: for allMatch no counterexample exists, and for noneMatch no example violating the condition exists. This rule often surprises, so it must be checked with a small program before use in an important validation.

findFirst returns the first element according to encounter order, when order exists; findAny permits any element to be chosen. Both return Optional<T> because the source or filter may produce nothing. The method orElse("no city") makes the answer explicit in that case. min and max also return an object Optional: an empty sequence has no minimum. count, conversely, has a defined result, zero. Seeing the return type helps us recognize whether absence must be handled.

forEach performs an action, so it is useful when the effect is precisely the requested result, for example sending every line to a consumer. It does not return a collection. To obtain a list, we use toList or collect; to obtain a typed array, toArray(String[]::new) supplies a factory of the right size. Collectors.joining(", ") concatenates strings with a separator; choosing a separator does not automatically add quoting or escape rules for CSV format. If the result must be a real CSV file, fields containing commas, quotes and newlines must be handled.

Reduction and Collection, with a Concrete Domain

The StreamCatalogDemo.java program uses four books, each with title, department, page count and availability. The first question is “which available titles do I show in order?”. The program filters available books, extracts titles, removes spaces at the edges, sorts and produces a list. The result is [Algebra, Algorithms, Java]. The method sequence follows the question: first we select books, then transform books into text, then clean and sort text. If we performed map(Book::title) before filtering on availability, we would have lost precisely the property needed by the filter.

The second question is “how many books are in each department?”. Collectors.groupingBy(Book::department, Collectors.counting()) produces a map: the key is the department, and the value the count. byDepartment.get("Computing") is 3. A simple groupingBy would instead produce a map of lists of books. The downstream collector counting changes the value type and avoids constructing lists when we want only a number. The program prints only the key of interest: we do not make a check depend on iteration order of a map for which we have requested no order guarantee.

The third question concerns total pages. mapToInt(Book::pages) moves from Book objects to primitive int values; summaryStatistics() calculates count, sum, minimum, maximum and average in a single terminal. The program uses count and sum and prints 4 books, 1150 pages. This is a practical case of “I want several summaries but cannot reuse the same stream”: statistics are a result object containing several measurements obtained from consuming the pipeline. If a chapter has zero books, some statistics such as average do not have the meaning they would have over a nonempty population; the caller must decide how to represent that absence.

The fourth question is “which available book has the fewest pages?”. After filtering, min(Comparator.comparingInt(Book::pages)) compares books according to the pages field and returns an Optional<Book>. map(Book::title) transforms the found book into its title; orElse("none") covers the case of a catalog without available books. The program's result is Algebra. The complete form applies the idea of Optional previewed in Chapter 16: a minimum may be missing and the caller must express what to do. Chapter 19 will develop this type and the choices for handling absence.

reduce is useful when we can combine two values of the same problem into a result of the same type. With reduce(0, Integer::sum), zero is the identity and addition combines partial results. If we use reduce to concatenate many strings with a + b, we potentially create many intermediate objects; Collectors.joining better communicates the purpose. collect is instead designed to accumulate elements into a result structure with a protocol of supplier, accumulator and combiner. The two operations are not universal synonyms. A well-chosen collector avoids sharing an external ArrayList between pipeline lambdas, especially if the pipeline becomes parallel.

Reducing and Collecting Results

A reduction combines several elements into a result. count() returns how many elements traverse the pipeline; reduce can combine numbers or other values with a compatible operation; collect uses a collector to construct a result, for example a map of groups. In the program, Collectors.groupingBy(String::length) groups words by length. Reading key 4 gives [Java, Nets]. We do not print the entire map relying on its order, because the general groupingBy contract promises no particular iteration order for the returned map.

Collectors.teeing applies two collectors to the same elements and combines results. The example counts seven numbers and sums their values, printing 7 elements, sum 24. The name does not imply two threads or two mandatory passes over the source: it indicates a combination of two logical collections. For a simple sum we would use mapToInt(...).sum(), which is shorter. The double collector is useful when two correlated aggregations are genuinely needed in the same result.

Important note – Identity and Associativity. To use reduce correctly, the initial value must behave as the operation's identity, and combination must be associative if we want splits and recombinations to produce the same result. For integer addition, 0 is the identity: 0 + x equals x. For subtraction, changing grouping can change the result. This limit becomes decisive when considering parallelism.

findFirst and findAny return Optional, previewed in Chapter 16 and developed further in Chapter 19; here it is enough to know that the result can be absent and must be handled. anyMatch, allMatch and noneMatch answer Boolean questions and can stop before the end. sorted sorts pipeline elements according to a comparator or natural order; if we need to know the original collection's order, we cannot infer it solely from the order produced by sorted.

A Reduction Read Element by Element

To sum 1, 2 and 3 we can write reduce(0, Integer::sum). The initial value 0 is the identity of addition: adding it does not alter the first element. The reduction combines 0 with 1 and obtains 1; combines 1 with 2 and obtains 3; combines 3 with 3 and obtains 6. It is not a magical shortcut that always performs exactly three calls in the described order: this reading shows the sequential case, while a parallel pipeline can subdivide work and recombine partial results. Addition is associative in mathematical arithmetic, but with int overflow remains possible; for quantities that may exceed the limit, an appropriate type or check is needed.

If we want to collect values in a list, the question changes: we seek a result structure rather than a single number. toList() directly expresses the request for an unmodifiable list; collect allows more elaborate collection strategies, such as grouping. Accumulating elements in an external ArrayList with effects in forEach can look similar on three numbers, but introduces shared state difficult to control if the pipeline changes. The distinction between reduction to a value, collection into a structure and external effect prepares a correct choice even when the pipeline grows long.

Richer Collections: Choosing the Final Structure

Collectors.toCollection(ArrayList::new) explicitly constructs a mutable list of the requested type; Collectors.toCollection(TreeSet::new) produces a sorted set eliminating duplicates according to its comparator. This is not a neutral conversion: two texts considered equivalent by the comparator can become a single element, even if they were two elements in the source. If duplicates must be preserved, a TreeSet does not represent the right result. Collectors.toMap requires a choice when two elements produce the same key: without a merge function, collision is an error, rather than a hidden library decision.

Suppose we want to associate each book's code with its title. If the catalog can contain two editions with the same code, we must establish whether the key is really unique, whether the first, last or a list of both should be retained. groupingBy(Book::code) expresses a map from code to list; toMap(Book::code, Book::title, (first, second) -> first) declares the “keep the first” policy. This last one is a domain decision that should not be hidden in an unexplained lambda. The final structure describes how we intend to handle collisions.

partitioningBy(predicate) creates two groups indexed by true and false, suitable for a binary split such as available and unavailable. groupingBy can instead produce many groups, one per department. mapping as downstream collector allows only titles to be collected inside each group; summingInt and averagingDouble calculate values per group without retaining every element. There is no need to memorize a combination list: we formulate the question, choose the key or predicate and then decide what we want inside each group.

Box – Summing Monetary Amounts. The numerical examples in the chapter use pages and counts, for which int or long are natural within declared limits. For money, double can introduce unwanted binary approximations. If the domain requires exact decimal amounts and rounding rules, we represent amounts with a suitable type such as BigDecimal and reduce them with an addition consistent with the contract. The stream does not decide the numerical model for us.

From the Numerical Value to the Primitive Stream

IntStream, LongStream and DoubleStream work with primitive values; the difference from Stream<Integer> is better understood by observing a calculation. The NumericStreamsDemo.java program starts from integers 1 through 4. IntStream.rangeClosed(1, 4) includes both bounds and produces four values; range(1, 4) would stop before 4. The first terminal sum() prints 10. For a second calculation, a new stream is created with a second call to rangeClosed: the consumed one is not reused. average() calculates the average, meaning sum 10 divided by four elements, and produces an OptionalDouble, because an empty sequence would have no average. In this case we know it is not empty and orElseThrow() returns 2.5.

In Figure 18.3 the four families share the BaseStream contract, but not the same element type. The three primitive specializations are not subclasses of Stream<T>: conversion from objects to primitives and back happens with methods such as mapToInt and boxed.

Stream families for objects and primitives
Figure 18.3 – Stream<T> processes objects; IntStream, LongStream and DoubleStream process the three primitives supported by specialized APIs.

The third pipeline applies map(number -> number * number) and obtains squares 1, 4, 9 and 16. boxed() transforms primitive values of the IntStream into Integer, so toList() produces a List<Integer> printed as [1, 4, 9, 16]. In the fourth pipeline the path goes in the opposite direction: Stream.of("2", "3") contains strings, mapToInt(Integer::parseInt) interprets them as integers and sum() returns 5. If a string does not represent a valid integer, parseInt throws an exception; the stream does not automatically convert it to zero or discard it. The caller decides whether to validate first or handle the error.

Primitive streams avoid boxing every element in the numerical path and offer terminals such as sum, average, min and max. They are not a stylistic obligation: if we work with domain objects, immediately transforming them into numbers can lose the operations' meaning. Any possible performance advantage also depends on real work. The first criterion remains making clear what enters, what leaves and why the type changes.

Choosing the Primitive Stream When the Problem Changes

The previous example showed IntStream on already available numbers. In the catalog, instead, we start from Book objects and retain them as such while the question concerns title and availability. mapToInt(Book::pages) makes the path numerical when we ask for page statistics. To directly construct a primitive stream we can use IntStream.of(1, 2, 3), starting from explicit values, or IntStream.range(1, 4), producing 1, 2, 3; rangeClosed(1, 4) also includes 4. Arrays.stream(int[]) again produces IntStream. Similar methods exist for long and double; the library does not offer a distinct stream for every Java primitive.

sum() returns the sum; average() produces OptionalDouble; min() and max() produce OptionalInt for IntStream. Optionality reminds us that an empty sequence has no average, minimum or maximum. Calling getAsInt() without checking presence on an empty stream causes an error; orElse, orElseThrow or isPresent make the choice visible. count() returns a long, also for primitive streams. If values may exceed the capacity of int, it is not enough that the element count is long: the sum must also use a suitable type or strategy. mapToLong(...).sum() can be a choice, but long overflow remains possible for extreme data.

boxed() converts IntStream into Stream<Integer> when we need a collection of wrappers or an object API. mapToInt follows the opposite direction from Stream<T> to an extracted or calculated numerical value. Both steps have a cost and meaning: if we perform mapToInt(...).boxed() immediately for no reason, we are probably complicating the path. In the program, mapToInt(Book::pages) is motivated by page statistics, while books remain objects up to the point where the number is necessary.

Gatherers: a Transformation with Memory

Some transformations need to remember previous elements. Gatherer is an abstraction for richer intermediate operations; the class Gatherers offers ready implementations. The APIs have been stable since Java 24 and are present in Java 25, as the official Gatherers documentation indicates. They do not require preview options in our program.

In the program, data.stream().gather(Gatherers.windowFixed(3)).toList() produces [[1, 2, 3], [4, 5, 6], [3]]. Every window collects up to three consecutive elements; the last can be shorter. This is a case where a simple map is insufficient, because the result depends on grouping several inputs. windowSliding produces overlapping windows; scan emits progressive accumulations; fold constructs a final accumulation according to its contract. mapConcurrent uses controlled concurrency for transformations suited to that model, but must be tackled together with costs, effects and the rules of the concurrency chapter. Learning streams does not require starting from a custom Gatherer: first we master source, common transformations and terminal.

Imagine that the three measurements of a window represent one day's data. With windowFixed(3), every measurement belongs to one group only, except for the incomplete final window. If instead we want to observe a moving average, today's measurement must also appear beside those of neighboring days: a sliding window is needed and we must decide what to do when there are not yet enough observations. Before changing methods, we write the expected groups for a small sequence and compare them with output. The criterion for reusing Gatherer is that the transformation depends on state or several stream elements; converting every title to uppercase still requires only map. A more powerful solution, applied to a problem that does not require it, merely makes the result harder to predict.

Encounter Order: the First Guarantee to Declare

A stream can have an encounter order determined by the source, such as the order of a List. Other sources promise none. Some terminals and collectors preserve order; others may not, especially in parallel. forEach on a parallel stream is not the tool for requesting ordered printing; forEachOrdered maintains encounter order when it exists, but this guarantee can reduce opportunities for parallel processing.

Encounter order is a source property influencing the answer to findFirst and printing with forEachOrdered. It does not automatically appear because we have written a pipeline. When we introduce parallelism, this distinction will remain decisive: imposing order can limit simultaneous work. Resource-closure responsibility, on the other hand, depends on the source and will be applied to the file pipeline at the end of the chapter.

Parallelism, Order and Resources in the Real Program

The stream model allows parallel execution to be requested with parallelStream() or parallel(), but does not make every pipeline faster. The library can divide the source into portions, work on them over several threads and combine results. This work has costs. A very short filter over a few strings can perform worse; a heavy calculation over a large, easily divisible source can benefit from a multicore machine. Required order and stateful operations, such as sorted, can reduce the advantage. There is no universal number of elements above which “it pays”: we must measure on representative data and hardware.

Parallelism does not mean the caller immediately regains control as with an asynchronous API. A terminal such as toList() returns when the result is ready, even if internal work was distributed. The pipeline must also respect non-interference rules: lambdas must not modify the non-concurrent source during traversal. They should normally be without state varying between elements. An external ArrayList to which every element adds a result is problematic: in parallel, updates can race against one another, and even sequentially the effect is hidden relative to the terminal's contract. toList() and collectors express collection without that risk.

A List has encounter order; a HashSet does not promise the order in which we see elements. findFirst therefore has a precise meaning when the source is ordered; on an unordered source we cannot predict a stable first element. findAny explicitly communicates that any suitable element is sufficient. forEach on a parallel pipeline does not promise that actions appear in encounter order, while forEachOrdered preserves it when it exists, paying the cost of that constraint. If print order is part of the result, collecting a sorted list and then printing it can be simpler to verify.

A stream created by Files.lines(path) uses an operating-system resource. The block try (Stream<String> lines = Files.lines(path)) { ... } guarantees closure even on exception. This is a direct application of Chapter 12: the pipeline processes lines, and try-with-resources manages the file lifecycle. Stream.toList() does not replace that block. Conversely, an in-memory list stream does not require a file to be closed. The Stream type is the same, but the source determines resource responsibility.

Method for Verifying a Pipeline. First write the question in English and the expected result on four elements. Mark the type after every step: Stream<Book>, then Stream<String>, then List<String>, or IntStream and finally a number. Check encounter order if relevant, the presence of external effects and the empty-source case. Change one datum and predict the new result before execution. Only afterwards evaluate whether a parallel pipeline makes sense and measure it.

A Pipeline for a Real Question

Suppose the catalog contains book entries and we want the titles of available volumes, without unnecessary spaces and sorted for printing. The question can become a pipeline: start from entries, filter available ones, extract the title with map, clean it with String::strip, sort it with sorted and collect it with toList. Every step must have a distinct meaning. If availability can change while the pipeline is running, a contract on the data snapshot or synchronization is also needed: the stream does not make a source that others modify without rules coherent.

If we only need to find an available book, constructing and sorting the whole list would be unnecessary work. A search with filter(...).findFirst() on an ordered source better expresses the requested result and can stop at the first suitable element. If order does not matter, findAny() communicates that freedom, especially in parallel. The difference between the methods is a semantic choice, rather than a micro-optimization to apply without asking which answer is correct.

The traditional loop can also remain the most readable solution. If every element requires a sequence of checks with different errors and state updates, compressing everything into five lambdas can hide the path we need to diagnose. The Stream API is strong when transformations and aggregations are clear as data operations. It is not a stylistic obligation imposed by modern Java.

Effects and Observation Order

peek allows observation of elements traversing a pipeline and is useful mainly for limited diagnostics. We do not use it to update state on which the result depends, because an intermediate operation may not be invoked as we expect in every pipeline. forEach is terminal and produces an effect for processed elements, but in parallel the execution order of actions does not necessarily coincide with encounter order. If output must have stable order, collecting in a list followed by ordered printing is often easier to reason about; forEachOrdered is available when that constraint really belongs to the pipeline.

A parallel reduction requires particular care with mutable containers. Writing from several lambdas into the same external ArrayList is not a correct way to collect results: it introduces shared state and can lose data or produce unpredictable behavior. A suitable collector manages accumulation according to its contract. But even a collector that works in parallel does not guarantee that the pipeline will be faster. The criterion remains correctness first, measurement afterwards.

Key concept – Declare Guarantees. For every pipeline, we ask what the source is, whether order matters, which functions only read data, which terminal produces the result and who closes any resources. These five questions are more useful than a memorized list of every Stream method.

A File Pipeline: from Resource to Result

Imagine a file with one word per line and a request to count those beginning with J. The calculation part can be lines.map(String::strip).filter(s -> s.startsWith("J")).count(). First, however, we must open the file with the appropriate charset and path and handle a possible I/O error. Files.lines(path) returns a stream linked to a resource; the try-with-resources block is therefore part of the solution, rather than an optional addition for unfortunate cases. The final count is a long; there is no need to materialize all lines in a list.

The complete program FileStreamDemo.java prepares data in a temporary folder, explicitly declares UTF-8 and keeps opening the stream inside countWordsWithJ. try-with-resources closes the resource even if filtering or reading throws an exception. The folder is removed in the finally block: the program leaves no test file in the project. The missing case is handled in the caller, where it is possible to decide whether to inform the user, retry or stop work.

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.util.stream.Stream;

public class FileStreamDemo {
    private static long countWordsWithJ(Path path) throws IOException {
        try (Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8)) {
            return lines.map(String::strip)
                    .filter(word -> word.startsWith("J"))
                    .count();
        }
    }

    public static void main(String[] args) throws IOException {
        Path folder = Files.createTempDirectory("stream-file-");
        Path words = folder.resolve("words.txt");
        Path empty = folder.resolve("empty.txt");
        try {
            Files.writeString(words, "Java\nNets\n JVM \n", StandardCharsets.UTF_8);
            Files.writeString(empty, "", StandardCharsets.UTF_8);
            System.out.println("Words with J: " + countWordsWithJ(words));
            System.out.println("Empty file: " + countWordsWithJ(empty));
            try {
                countWordsWithJ(folder.resolve("absent.txt"));
            } catch (NoSuchFileException error) {
                System.out.println("Absent file: " + error.getClass().getSimpleName());
            }
        } finally {
            Files.deleteIfExists(words);
            Files.deleteIfExists(empty);
            Files.deleteIfExists(folder);
        }
    }
}

Compile with javac --release 25 -Xlint:all -d build FileStreamDemo.java and run java -cp build FileStreamDemo. You obtain Words with J: 2, Empty file: 0 and Absent file: NoSuchFileException. The first result follows the three lines Java, Nets, JVM: strip removes outer spaces and the second word with J becomes JVM. The empty file provides no elements to the pipeline. In the third case the resource does not open: NoSuchFileException is not a count of zero. The test transfers the already known filter to an I/O source and adds new responsibilities: charset, opening, closure and handling absence. If we read the same file twice for two questions, we open it twice or define a data-retention strategy; we do not reuse the closed stream.

To Verify

Compile StreamDemo.java with javac --release 25 -Xlint:all -d build StreamDemo.java and run it. First predict the six lines: the filtered list, the still-intact source, flattened words, windows, length-4 group and the result of both aggregations. Also compile StreamCatalogDemo.java and predict available titles, the Computing department count and page sum. Then change the window from 3 to 2 and explain why the last group is shorter. Finally try retaining a stream in a variable and invoking toList() twice on it: explain which lifecycle rule you violated.

Try the examples

Running the programs requires JDK 25. Download the individual Java files linked in the chapter or the complete example project, which includes instructions and a launcher script. The explanations also compare expected output: predict it before running the program.

Massimiliano Tarquini · CC BY-NC 4.0

Back to the top ↑