← All posts

Software engineering · java · streams · functional-programming · jvm · performance

The Java Streams API: From First Pipeline to Spliterators and Parallel Execution

How the Java Streams API works, from filter, map and collect to laziness, collectors, primitive streams, the Sink chain, spliterators, parallel streams and gatherers, explained from the basics up to what senior engineers need to know.

An assembly line for data

Picture a sandwich shop at lunchtime. Orders come in on slips of paper. One person throws away the slips for items that are sold out, the next makes each sandwich, the next wraps it, and the last person hands the first ten to the waiting customers. Nobody makes all the sandwiches first and then wraps them all. Each slip travels down the line on its own, and once ten customers have their food, the line stops, even if more slips are waiting.

A Java stream is that assembly line. You describe the stations, and Java moves your data through them:

List<String> names = orders.stream()            // where the slips come from
        .filter(o -> o.paid())                   // throw away unpaid orders
        .map(o -> o.customer())                  // turn each order into a name
        .distinct()                              // each customer once
        .limit(10)                               // only the first ten
        .toList();                               // hand them over

A stream isn’t a container. It stores nothing of its own. It describes work to do on data that lives somewhere else, in a list, a file, a range of numbers or a generator. Nothing happens until the last line asks for a result, and then each element goes down the line one at a time.

Java 8 (2014) added streams together with lambdas, and they changed how most Java code processes collections. They are easy to start with and full of details that matter at scale: why a stream can only be used once, why peek sometimes prints nothing, why toMap throws on a duplicate key, how a pipeline is fused into a single pass, and when parallel() makes things slower. This article goes from the first pipeline to those edges. It builds on Java Lambdas and Functional Interfaces, since every station in the line is a lambda.

The basics: from loops to pipelines

Here is the same task written as a loop and as a stream: the total of paid orders over 100, per customer.

record Order(String id, String customer, double amount, boolean paid) {}

// A loop: say how to do it
Map<String, Double> totals = new HashMap<>();
for (Order o : orders) {
    if (o.paid() && o.amount() > 100) {
        totals.merge(o.customer(), o.amount(), Double::sum);
    }
}

// A stream: say what you want
Map<String, Double> totals2 = orders.stream()
        .filter(o -> o.paid() && o.amount() > 100)
        .collect(Collectors.groupingBy(Order::customer,
                 Collectors.summingDouble(Order::amount)));

The loop mixes three concerns: walking the list, deciding what to keep and building the result. The stream separates them, and each step reads as a sentence. This is the real benefit. Streams are not faster than loops (we’ll come back to that); they are easier to read and harder to get subtly wrong once the logic has more than two or three steps.

Every pipeline has three parts:

Part What it is Examples
Source Where elements come from list.stream(), Stream.of(...), IntStream.range(0, n), Files.lines(path)
Intermediate operations Stations that transform the stream and return a new stream filter, map, flatMap, sorted, distinct, limit
Terminal operation The step that produces a result and starts the work toList, collect, count, forEach, reduce, findFirst

There can be any number of intermediate operations and exactly one terminal operation.

Laziness: nothing happens until you ask

Intermediate operations don’t do anything. They only add a station to the line. This code prints nothing at all:

Stream<String> s = Stream.of("a", "b", "c")
        .map(x -> { System.out.println("map " + x); return x.toUpperCase(); });
// no output: there is no terminal operation

When a terminal operation runs, elements flow through one at a time, through every station, not one station at a time over every element:

Stream.of("apple", "banana", "cherry", "date")
        .filter(s -> { System.out.println("filter " + s); return s.length() > 4; })
        .map(s -> { System.out.println("map    " + s); return s.toUpperCase(); })
        .findFirst();
filter apple
map    apple

banana, cherry and date are never looked at. findFirst got its answer from the first element, so the whole line stopped. This is called short-circuiting, and it is why laziness matters: a loop-per-step implementation would have filtered all four words and uppercased three before taking the first.

Diagram: four elements, apple, banana, cherry and date, enter a pipeline of filter, map and findFirst. Apple travels through filter and map to findFirst, which has its answer and stops the pipeline. Banana, cherry and date are never pulled from the source

Laziness also makes infinite streams possible, as long as something downstream stops them:

Stream.iterate(1, n -> n * 2)    // 1, 2, 4, 8, ... forever
        .limit(10)
        .forEach(System.out::println);

A stream can be used only once

Once a terminal operation has run, the stream is spent. Using it again throws:

Stream<String> s = names.stream();
s.count();
s.count();   // IllegalStateException: stream has already been operated upon or closed

This follows from the assembly-line model: a stream is a single trip over its source, not a reusable view. If you need to run two queries, call names.stream() twice, or keep a Supplier<Stream<String>> that builds a fresh one.

Creating streams

Source Code Notes
Any collection list.stream(), set.stream() The most common source
A map map.entrySet().stream() Maps aren’t collections; stream their entries, keys or values
Fixed values Stream.of("a", "b") Stream.ofNullable(x) gives zero or one element (Java 9)
An array Arrays.stream(arr) Primitive arrays give IntStream, LongStream or DoubleStream
A range of numbers IntStream.range(0, 10), rangeClosed(1, 10) No boxing; splits well for parallel work
Generated values Stream.generate(UUID::randomUUID) Infinite; needs limit
A sequence Stream.iterate(1, n -> n < 1000, n -> n * 2) A for loop as a stream (three-argument form, Java 9)
Lines of a file Files.lines(path) Holds the file open; close it (see below)
Text "a,b,c".chars(), Pattern.compile(",").splitAsStream(s), s.lines() chars() gives an IntStream of characters
Many streams Stream.concat(a, b) Deeply nested concat can overflow the stack; prefer Stream.of(a, b, c).flatMap(s -> s)
Built by hand Stream.<String>builder().add("x").build() Rarely needed

Intermediate operations

Operation What it does Kind
filter(p) Keep elements that match Stateless
map(f) Turn each element into one other value Stateless
mapToInt(f), mapToObj(f), boxed() Switch between object and primitive streams Stateless
flatMap(f) Turn each element into a stream and join them all Stateless
mapMulti(fn) Turn each element into zero or more values by pushing them (Java 16) Stateless
peek(action) Look at each element as it passes; for debugging Stateless
distinct() Drop duplicates, using equals and hashCode Stateful
sorted(), sorted(cmp) Sort Stateful, and a barrier
limit(n), skip(n) Keep the first n, or drop the first n Stateful, short-circuiting (limit)
takeWhile(p), dropWhile(p) Keep or drop elements until the predicate first fails (Java 9) Stateful, short-circuiting (takeWhile)
gather(g) Any custom intermediate step (Java 24) Depends on the gatherer

The stateless operations look at one element and forget it. The stateful ones remember something across elements: distinct keeps a set of everything it has seen, and sorted keeps everything, because it can’t emit the smallest element until it has seen the last one. That makes sorted a barrier: the stream goes in one at a time and comes out one at a time, but in between it is a full list in memory.

Stream.of(3, 1, 2)
        .peek(n -> System.out.println("before " + n))
        .sorted()
        .peek(n -> System.out.println("after  " + n))
        .forEach(n -> {});
before 3
before 1
before 2
after  1
after  2
after  3

map versus flatMap

map is one-in, one-out. flatMap is one-in, many-out: each element becomes a stream of its own, and the results are joined into one stream.

record Customer(String name, List<Order> orders) {}

List<Order> allOrders = customers.stream()
        .flatMap(c -> c.orders().stream())   // Stream<Customer> -> Stream<Order>
        .toList();

List<String> words = lines.stream()
        .flatMap(line -> Arrays.stream(line.split("\\s+")))
        .toList();

A common use is dropping empty results: Optional has a stream() method that gives zero or one element, so .flatMap(id -> lookup(id).stream()) keeps only the ids that were found.

mapMulti (Java 16) does the same job without creating a small stream for every element. You get a consumer and push as many values as you like into it:

List<Order> allOrders2 = customers.stream()
        .<Order>mapMulti((c, sink) -> c.orders().forEach(sink))
        .toList();

It is faster when each element produces only a few values, and it handles cases that would be awkward as a stream, such as “emit this element twice if it matches, otherwise nothing”. The explicit <Order> is needed because the compiler can’t infer the output type from the lambda.

takeWhile and dropWhile

filter looks at every element. takeWhile stops at the first element that fails, which makes it the right tool for sorted or time-ordered data:

// log lines are in time order: stop reading at the first line after the cut-off
logLines.stream()
        .takeWhile(l -> l.timestamp().isBefore(cutoff))
        .forEach(this::process);

On an unordered source, “the first element that fails” has no stable meaning, so the result can differ from run to run.

Terminal operations

Operation Result Short-circuits
toList() An unmodifiable List (Java 16) No
collect(collector) Whatever the collector builds: a map, a set, a string No
toArray(), toArray(String[]::new) An array No
forEach(action), forEachOrdered(action) Nothing; runs the action on each element No
count() long No
min(cmp), max(cmp) Optional<T> No
reduce(...) One combined value No
anyMatch, allMatch, noneMatch boolean Yes
findFirst(), findAny() Optional<T> Yes

The match operations stop as soon as they know the answer. anyMatch stops at the first match, allMatch at the first element that doesn’t match. On an empty stream, allMatch and noneMatch return true and anyMatch returns false, which is logically correct and still surprises people.

toList() versus Collectors.toList()

They look the same and are not:

  stream.toList() collect(Collectors.toList()) collect(Collectors.toUnmodifiableList())
Can you add to it? No Yes, today (it is an ArrayList), but the specification doesn’t promise it No
Allows null elements? Yes Yes No, throws NullPointerException
Since Java 16 Java 8 Java 10

Use toList() by default. If the caller needs to change the list, say so explicitly with collect(Collectors.toCollection(ArrayList::new)), rather than relying on what Collectors.toList() happens to return today.

reduce

reduce combines all elements into one value with a function you provide:

int sum = numbers.stream().reduce(0, Integer::sum);           // identity and accumulator
Optional<Integer> max = numbers.stream().reduce(Integer::max); // no identity: may be empty

The identity must really be neutral: combining it with any value must give that value back. 0 is the identity for addition, 1 for multiplication and "" for string concatenation. And the function must be associative: (a + b) + c must equal a + (b + c). A sequential stream doesn’t care, but a parallel stream splits the work and combines the parts in an order you don’t control, so a wrong identity or a non-associative function gives wrong answers only when you go parallel. Subtraction is the classic trap: reduce(0, (a, b) -> a - b) gives different results sequentially and in parallel.

In practice, prefer the specialised operations: mapToInt(...).sum(), max(...), count() or a collector. They say what you mean, and the primitive versions don’t box.

Collectors: building the result

collect takes a Collector, a recipe for building a result container. The Collectors class has dozens of ready-made ones, and the useful ones are worth knowing by heart.

// To collections
Set<String> customers   = orders.stream().map(Order::customer).collect(Collectors.toSet());
TreeSet<String> sorted  = orders.stream().map(Order::customer)
                                .collect(Collectors.toCollection(TreeSet::new));

// To a string
String csv = orders.stream().map(Order::id).collect(Collectors.joining(", ", "[", "]"));

// To a map, one entry per element
Map<String, Order> byId = orders.stream().collect(Collectors.toMap(Order::id, o -> o));

toMap has two traps

// 1. Duplicate keys throw IllegalStateException:
//    Duplicate key alice (attempted merging values 10.0 and 200.0)
Map<String, Double> byCustomer = orders.stream()
        .collect(Collectors.toMap(Order::customer, Order::amount));

// Fix: say how to merge two values for the same key
Map<String, Double> byCustomer2 = orders.stream()
        .collect(Collectors.toMap(Order::customer, Order::amount, Double::sum));

// 2. A null value throws NullPointerException, even though HashMap allows null values
Map<String, String> notes = orders.stream()
        .collect(Collectors.toMap(Order::id, o -> lookupNote(o)));   // NPE if any note is null

The second one surprises people because HashMap allows null values. toMap follows the rules of Map.merge, where a null value means “remove this key”, so it rejects nulls outright instead of guessing. If you need nulls, collect with a loop or wrap the value in an Optional.

There is a four-argument version that also takes the map to build: toMap(Order::id, o -> o, (a, b) -> a, LinkedHashMap::new) keeps the stream’s order.

groupingBy and downstream collectors

groupingBy is the SQL GROUP BY of streams. On its own, it builds a Map<K, List<T>>:

Map<String, List<Order>> byCustomer = orders.stream()
        .collect(Collectors.groupingBy(Order::customer));

Its real power is the second argument, a downstream collector that decides what to do with each group instead of putting it in a list:

// How many orders per customer
Map<String, Long> counts = orders.stream()
        .collect(Collectors.groupingBy(Order::customer, Collectors.counting()));

// Total spend per customer
Map<String, Double> spend = orders.stream()
        .collect(Collectors.groupingBy(Order::customer, Collectors.summingDouble(Order::amount)));

// The biggest order per customer
Map<String, Optional<Order>> biggest = orders.stream()
        .collect(Collectors.groupingBy(Order::customer,
                 Collectors.maxBy(Comparator.comparingDouble(Order::amount))));

// Order ids per customer, in a sorted map
Map<String, List<String>> ids = orders.stream()
        .collect(Collectors.groupingBy(Order::customer, TreeMap::new,
                 Collectors.mapping(Order::id, Collectors.toList())));

// Two levels: paid and unpaid, then per customer
Map<Boolean, Map<String, Long>> nested = orders.stream()
        .collect(Collectors.partitioningBy(Order::paid,
                 Collectors.groupingBy(Order::customer, Collectors.counting())));

Diagram: six orders flow into groupingBy by customer, which sorts them into three buckets, alice, bob and carol. Each bucket feeds its own copy of the downstream collector, summingDouble of amount, which produces one total per customer in the result map

Downstream collectors compose like the functions in a SQL SELECT: counting, summingInt, averagingDouble, minBy, maxBy, mapping, filtering (Java 9), flatMapping (Java 9), reducing, joining, toSet and another groupingBy. partitioningBy is a groupingBy with a boolean key that always has both true and false entries, even when one is empty.

filtering is subtly different from a filter before the groupingBy. Filtering first drops elements, so a customer with no matching orders disappears from the map. Filtering downstream keeps the customer with an empty group:

// alice -> [big orders], bob is missing if he has none
orders.stream().filter(o -> o.amount() > 100)
      .collect(Collectors.groupingBy(Order::customer));

// alice -> [big orders], bob -> []
orders.stream()
      .collect(Collectors.groupingBy(Order::customer,
               Collectors.filtering(o -> o.amount() > 100, Collectors.toList())));

Two more that are worth knowing:

// teeing (Java 12): run two collectors over the same elements and combine the results
record Range(double min, double max) {}
Range range = orders.stream().map(Order::amount)
        .collect(Collectors.teeing(
                Collectors.minBy(Double::compare),
                Collectors.maxBy(Double::compare),
                (min, max) -> new Range(min.orElse(0.0), max.orElse(0.0))));

// collectingAndThen: finish the result, here to make it unmodifiable
List<String> frozen = orders.stream().map(Order::id)
        .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList));

The maps that groupingBy builds are HashMaps by default, so iteration order is not the order of the stream. If order matters, pass LinkedHashMap::new or TreeMap::new as the map factory. The trade-offs between those maps are covered in Understanding Java Collections.

Primitive streams

Stream<Integer> holds Integer objects. Every arithmetic step unboxes, computes and boxes again. For numeric work, use the three primitive streams, IntStream, LongStream and DoubleStream:

double total = orders.stream().mapToDouble(Order::amount).sum();   // no boxing

IntSummaryStatistics stats = words.stream().mapToInt(String::length).summaryStatistics();
// count, sum, min, average and max in a single pass

List<Integer> squares = IntStream.rangeClosed(1, 5)
        .map(n -> n * n)
        .boxed()               // back to Stream<Integer> when you need objects
        .toList();

Primitive streams have sum, average, summaryStatistics, range and asLongStream, which object streams lack. There is no CharStream, ShortStream or FloatStream: chars() gives an IntStream, and you cast back with mapToObj(c -> (char) c).

The difference is real. Summing ten million numbers as Stream<Integer> allocates up to ten million Integer objects (the JVM caches only -128 to 127), while IntStream allocates none. The reason Java needs separate primitive streams at all, instead of Stream<int>, is erasure, explained in Understanding Java Generics.

Optional results

Operations that may find nothing, such as findFirst, min, max and reduce without an identity, return an Optional:

String name = orders.stream()
        .filter(o -> o.amount() > 1_000)
        .map(Order::customer)
        .findFirst()
        .orElse("nobody");

Use orElse for a constant, orElseGet(() -> ...) for a value that is expensive to compute, and orElseThrow() when nothing found is a bug. Avoid get() without a check, which is the same NoSuchElementException waiting to happen as null was.

Side effects and closing streams

Keep lambdas free of side effects

The lambdas you pass to filter, map and friends should only compute. Writing to outside state from inside a stream works in simple sequential code and breaks the moment the stream goes parallel:

// Wrong: ArrayList is not thread-safe, and in parallel this loses elements or throws
List<String> result = new ArrayList<>();
orders.parallelStream().map(Order::id).forEach(result::add);

// Right: let the stream build the result
List<String> result2 = orders.parallelStream().map(Order::id).toList();

The documentation calls the requirement non-interference: don’t modify the source while the stream runs. list.stream().forEach(x -> list.add(x)) throws ConcurrentModificationException on an ArrayList, and on a concurrent collection it may or may not see the new elements.

Some streams must be closed

Most streams don’t hold resources. Streams from Files.lines, Files.list, Files.walk and JDBC-backed sources do: they keep a file handle or a cursor open until closed. Stream implements AutoCloseable, so use try-with-resources:

try (Stream<String> lines = Files.lines(Path.of("access.log"))) {
    long errors = lines.filter(l -> l.contains(" 500 ")).count();
}

Forgetting this leaks file handles, which in a long-running service ends in “Too many open files”. onClose(Runnable) lets you attach your own cleanup to a stream you return.

Checked exceptions

The functional interfaces streams use don’t declare checked exceptions, so map(path -> Files.readString(path)) doesn’t compile. Wrap the call and rethrow as UncheckedIOException, or collect results and failures separately. The options are covered in detail in the lambdas article.

The mistakes everyone makes

  • Expecting peek to always run. peek is for debugging, and the stream is allowed to skip it. Since Java 9, List.of(1, 2, 3).stream().peek(System.out::println).count() prints nothing, because count can read the size straight from the list without running the pipeline.
  • Using forEach to build results. Adding to an outside list or map from forEach is a loop in disguise and breaks in parallel. Use toList() or collect.
  • Sorting before filtering. sorted().filter(...) sorts everything, then throws most of it away. Filter first.
  • toMap without a merge function on keys that might repeat. It works in tests and throws in production when a duplicate shows up.
  • Reusing a stream. Store a Supplier<Stream<T>> or the source collection, not the stream.
  • Returning Stream from a method that holds a resource, without making it clear the caller must close it.
  • stream().count() > 0 to check for any element. Use anyMatch or !list.isEmpty(); count walks everything.
  • Stream<Integer> for arithmetic. Use mapToInt, mapToLong or mapToDouble.
  • Very long chains of map with block lambdas. If a pipeline step needs ten lines, it needs a name. Extract a method and pass a method reference.
  • Writing parallel() because it sounds faster. See the section on parallel streams before you do.

Advanced ideas

Everything above is enough to use streams well. The rest of this article explains how they work inside, which is what you need when you are tuning a hot path, reviewing a parallel pipeline or designing a library.

How a pipeline is built: stages and sinks

When you write list.stream().filter(p).map(f).toList(), the JDK builds a linked list of pipeline stages. list.stream() creates the head (ReferencePipeline.Head), holding the source’s Spliterator. Each intermediate call creates a new stage object that points back to the previous one and records the operation. No elements move yet.

Each stage also records stream flags: whether the stream is SIZED (the count is known), ORDERED, DISTINCT or SORTED. Operations read and change these flags. filter clears SIZED, because it can’t know how many elements will survive. sorted() on a stream already flagged SORTED does nothing at all. distinct() on a stream from a Set is a no-op for the same reason. This is how count() on a List can skip the pipeline: the stream is SIZED and nothing in between changes the count, so the answer is the size.

When the terminal operation runs, the stages are turned into a chain of Sinks. A Sink is a Consumer with three extra methods: begin(size), end() and cancellationRequested(). Starting from the terminal operation and walking backwards, each stage wraps the next stage’s sink in its own:

  • filter’s sink calls the downstream accept only if the predicate matches.
  • map’s sink calls the downstream accept with f.apply(x).
  • sorted’s sink buffers every element in accept, then sorts and pushes them all downstream in end.
  • limit’s sink counts, and reports cancellationRequested() == true once it has enough.

Then the source spliterator pushes each element into the first sink:

// Pseudocode for what the terminal operation does
sink.begin(knownSizeOrMinusOne);
if (pipeline has no short-circuiting stage) {
    source.forEachRemaining(sink);              // push everything
} else {
    while (!sink.cancellationRequested() && source.tryAdvance(sink)) {
        // push one element at a time, checking for "stop" in between
    }
}
sink.end();

Diagram: the pipeline list.stream().filter(p).map(f).toList() at build time is a chain of stage objects, Head, filter, map and toList, each pointing to the previous one. At run time the stages become nested sinks: the source spliterator calls filter's accept, which calls map's accept only if p matches, which calls the toList sink's accept with f applied. One element at a time passes through the whole chain in a single call stack

This is loop fusion. The whole pipeline becomes one pass over the data, with each element travelling down a stack of nested accept calls. There are no intermediate lists between filter and map. Only stateful operations like sorted buffer.

A consequence for performance: the JIT sees a deep chain of calls through interfaces (Sink.accept, Predicate.test, Function.apply). When the pipeline is small, used in one place and hot, the JIT inlines all of it and the result is close to a hand-written loop. When the same stream code runs with many different lambdas, the call sites become megamorphic and the JIT gives up on inlining, as described in the lambdas article. That is one reason benchmarks of streams versus loops disagree so much.

Spliterators: how a source feeds a stream

Every stream starts from a Spliterator (“splittable iterator”), the source’s side of the contract:

// The core of java.util.Spliterator, abridged, with our own comments
public interface Spliterator<T> {
    boolean tryAdvance(Consumer<? super T> action);   // push one element, if any
    void forEachRemaining(Consumer<? super T> action); // push the rest (default loops tryAdvance)
    Spliterator<T> trySplit();                        // hand off part of the work, or null
    long estimateSize();
    int characteristics();                            // ORDERED, SIZED, SUBSIZED, SORTED, DISTINCT, ...
}

Note that a spliterator pushes elements to a consumer instead of returning them like Iterator.next(). One tryAdvance call replaces the hasNext/next pair, which is simpler to implement correctly and cheaper to call.

trySplit is what parallel streams are built on. An ArrayList spliterator splits its index range in half: cheap, and both halves are exactly sized (SUBSIZED). A HashMap splits its bucket array. A LinkedList can’t jump to its middle, so it splits by copying a batch of elements into an array, which is slow and uneven. Stream.iterate can’t split at all, because each element depends on the one before it.

You can write your own spliterator to stream over a custom source. Most of the time, extending Spliterators.AbstractSpliterator and implementing only tryAdvance is enough:

// Stream the pages of a paginated API, lazily, one page request at a time
static Stream<Item> allItems(ApiClient client) {
    Spliterator<Item> s = new Spliterators.AbstractSpliterator<>(Long.MAX_VALUE, Spliterator.ORDERED) {
        private String cursor = null;
        private Iterator<Item> page = Collections.emptyIterator();
        private boolean done = false;

        @Override
        public boolean tryAdvance(Consumer<? super Item> action) {
            while (!page.hasNext()) {
                if (done) return false;
                Page p = client.fetch(cursor);
                page = p.items().iterator();
                cursor = p.nextCursor();
                done = (cursor == null);
            }
            action.accept(page.next());
            return true;
        }
    };
    return StreamSupport.stream(s, false);
}

Now allItems(client).filter(...).limit(50).toList() fetches only as many pages as it needs for 50 matching items, which is laziness doing real work. AbstractSpliterator’s trySplit splits off batches into arrays, so this even works in parallel, if not very well.

Parallel streams

parallelStream() or .parallel() runs the same pipeline on several threads. The JDK splits the source with trySplit into a tree of chunks, runs the pipeline on each chunk as a fork/join task, and combines the partial results:

Diagram: a source of 1,000,000 elements is split by trySplit into two halves, then quarters, down to leaf chunks of about 31,000 elements. Each leaf chunk runs the whole fused pipeline on a ForkJoinPool worker thread and produces a partial result. Partial results are combined pairwise back up the tree into the final result. Splitting stops at roughly four leaf tasks per core

The tasks run on the common ForkJoinPool, shared by the whole JVM, with one fewer worker than the number of cores (the calling thread helps too). Splitting continues until a chunk is smaller than about size / (4 × parallelism), so there are roughly four leaf tasks per worker, enough for work stealing to balance uneven chunks.

Whether this is faster depends on whether the work outweighs the cost of splitting, scheduling and combining. A widely quoted rule of thumb from Doug Lea, the author of the fork/join framework: multiply the number of elements N by the cost per element Q. When N × Q is below about 10,000 (with Q measured roughly in simple operations), parallel is unlikely to help. Summing a list of a thousand integers in parallel is slower than doing it sequentially.

Parallel works well when:

  • The source splits well: arrays, ArrayList, IntStream.range, HashMap and HashSet. It works badly for LinkedList, Stream.iterate, Files.lines (better since Java 9, but still limited) and anything from an Iterator.
  • The work per element is CPU-bound and meaningful, not a field read.
  • Combining is cheap: summing numbers is cheap; merging large HashMaps from every chunk is not, which is why groupingBy in parallel often disappoints. groupingByConcurrent writes into one ConcurrentHashMap instead, at the cost of order.
  • There is no blocking I/O. A parallel stream that calls a database or an HTTP service blocks common-pool threads, and every other parallel stream and CompletableFuture.supplyAsync in the JVM queues behind it.

Encounter order and its cost

A stream from a List or an array has an encounter order; one from a HashSet doesn’t. Operations respect that order when it exists, and in parallel, keeping it costs:

  • findFirst must wait until every chunk to the left has reported; findAny can return the first result any thread finds.
  • limit(n) on an ordered parallel stream must buffer to know which n elements came first. On an unordered stream it takes any n.
  • distinct and sorted must preserve or establish order across chunks.
  • forEach in parallel runs in whatever order threads reach elements; forEachOrdered restores encounter order and gives up most of the parallelism to do it.

If you don’t need order, say so with .unordered(), and limit, distinct and findAny get cheaper. A collector can say the same with the UNORDERED characteristic.

Running a parallel stream in your own pool

Because the common pool is shared, a long parallel stream in one request can slow down unrelated work everywhere else in the service. A well-known workaround is to start the stream from inside a task in your own pool:

ForkJoinPool pool = new ForkJoinPool(8);
List<Result> results = pool.submit(() ->
        inputs.parallelStream().map(this::compute).toList()
).get();

This works because fork/join tasks fork into the pool of the thread that runs them. It is, however, an implementation detail, not a documented guarantee. Use it consciously, and for I/O-bound work prefer an executor of virtual threads (Java 21) or Gatherers.mapConcurrent (below), which are designed for it.

Writing your own Collector

A Collector is four functions and a set of flags:

Part Role For toList()-like behaviour
supplier Create an empty container ArrayList::new
accumulator Add one element to a container List::add
combiner Merge two containers (only used in parallel) (a, b) -> { a.addAll(b); return a; }
finisher Turn the container into the result identity
characteristics IDENTITY_FINISH, UNORDERED, CONCURRENT IDENTITY_FINISH

Here is a collector that keeps the top N elements by some comparator, using a bounded heap instead of sorting everything:

static <T> Collector<T, ?, List<T>> topN(int n, Comparator<? super T> cmp) {
    return Collector.of(
            () -> new PriorityQueue<T>(cmp),                     // min-heap of the best so far
            (heap, x) -> { heap.offer(x); if (heap.size() > n) heap.poll(); },
            (a, b) -> { for (T x : b) { a.offer(x); if (a.size() > n) a.poll(); } return a; },
            heap -> { List<T> out = new ArrayList<>(heap); out.sort(cmp.reversed()); return out; });
}

List<Order> top3 = orders.stream().collect(topN(3, Comparator.comparingDouble(Order::amount)));

This is O(N log n) time and O(n) memory, against O(N log N) and O(N) for sorted(...).limit(n). Note Comparator<? super T>: a collector for Order should accept a comparator written for any supertype, which is the PECS rule from the generics article.

The combiner must be correct even though sequential code never calls it. A collector that works sequentially and silently gives wrong answers in parallel because nobody tested the combiner is a classic bug. Write one test that runs it on a parallel stream.

Gatherers: custom intermediate operations

Collectors let you write any terminal operation; until recently there was no way to write your own intermediate one. Windowing, running totals and “deduplicate by key” all needed awkward workarounds. Stream gatherers, previewed in Java 22 and final in Java 24 (JEP 485), fill that gap with a new operation, gather, and a set of ready-made gatherers:

// Fixed windows: [1, 2, 3], [4, 5, 6], [7]
Stream.of(1, 2, 3, 4, 5, 6, 7).gather(Gatherers.windowFixed(3)).toList();

// Sliding windows: [1, 2, 3], [2, 3, 4], [3, 4, 5]
Stream.of(1, 2, 3, 4, 5).gather(Gatherers.windowSliding(3)).toList();

// Running totals: 1, 3, 6, 10
Stream.of(1, 2, 3, 4).gather(Gatherers.scan(() -> 0, Integer::sum)).toList();

// Call a slow service with at most 16 calls in flight, keeping the order
urls.stream().gather(Gatherers.mapConcurrent(16, this::fetch)).toList();

mapConcurrent runs each call on a virtual thread, so it is the right tool for I/O fan-out in a stream, where a parallel stream is the wrong one.

Writing your own gatherer means providing an optional state, an integrator that receives each element and pushes zero or more results downstream, and an optional finisher. Here is “keep the first element for each key”, a distinctBy that the standard library doesn’t have (JEP 485 itself uses distinct-by-key as a motivating case):

static <T, K> Gatherer<T, ?, T> distinctBy(Function<? super T, ? extends K> key) {
    return Gatherer.ofSequential(
            HashSet<K>::new,
            Gatherer.Integrator.ofGreedy((seen, element, downstream) -> {
                if (seen.add(key.apply(element))) {
                    return downstream.push(element);
                }
                return true;
            }));
}

orders.stream().gather(distinctBy(Order::customer)).toList();   // first order per customer

The integrator returns false to stop the stream early, which is how a gatherer short-circuits. ofGreedy tells the stream it never will, which allows some optimisations.

Streams versus loops: what the benchmarks say

Streams have a fixed cost: building the stages, the sink chain, a few objects and the interface calls. For a handful of elements that cost dominates, and a loop is faster. For large inputs on a hot path, a simple pipeline that the JIT has fully inlined is usually within a small factor of a loop, sometimes equal. Primitive streams close most of the remaining gap, and boxing widens it again.

The honest guidance:

  • Write streams for clarity in ordinary code. The cost is noise next to I/O, allocation elsewhere and serialization.
  • On a measured hot path, benchmark with JMH, not with System.nanoTime around a single run, which mostly measures warm-up.
  • Watch for allocation more than for call overhead: boxing, flatMap creating many small streams, collect into big intermediate maps.
  • A tight loop over a primitive array is where loops win most clearly, and where IntStream versus for is worth measuring.

Return Stream or Collection?

Joshua Bloch’s advice in Effective Java (item 47) holds up: prefer returning a Collection (usually a List) from public APIs. A collection can be iterated, streamed, sized and indexed; a stream can only be streamed, once.

Return a Stream when the results are large or infinite, expensive to compute in full, or backed by a resource, so that the caller decides how much to consume. Repository methods that read from a database cursor are the classic case. Then document that the stream must be closed, and close the underlying resource with onClose.

When a method takes many elements as input, take a Collection<? extends T> or an Iterable, not a Stream, unless the input really might be lazy or huge.

How Java compares

Language Equivalent Notable difference
Kotlin Sequence (lazy), collection operators (eager) Collection map/filter are eager by default; asSequence() makes them lazy
C# LINQ Query syntax as well as methods; IEnumerable can be enumerated again
Scala View, LazyList, collection operators Rich collections with eager operators; laziness is opt-in
Rust Iterator adapters Zero-cost: generics are monomorphised, so pipelines compile to loops
JavaScript Array methods, iterator helpers Array.map and filter are eager and build a new array at each step

Don’t confuse Java streams with reactive streams (Flow, Reactor, RxJava). Java streams are pull-driven from the source and synchronous: the terminal operation runs to completion on the calling thread or the fork/join pool. Reactive streams handle asynchronous elements that arrive over time, with back-pressure.

Key takeaways

  • A stream is a description of work over a source, made of intermediate operations and one terminal operation. It holds no data and can be used only once.
  • Nothing happens until the terminal operation, and then each element passes through every stage before the next one starts. That makes short-circuiting and infinite streams possible.
  • Prefer toList(), give toMap a merge function, and learn groupingBy with downstream collectors: it replaces most hand-written aggregation loops.
  • Use primitive streams for numbers; Stream<Integer> boxes every value.
  • Keep lambdas free of side effects, close streams that hold resources, and don’t rely on peek running.
  • Inside, a pipeline is a chain of stages turned into nested sinks, fused into a single pass. Stream flags let the JDK skip work, such as running count() without the pipeline.
  • Parallel streams help only for large, CPU-bound work over sources that split well, run on the shared common pool, and pay extra to keep encounter order. Measure before using them.
  • Write a Collector for custom terminal operations and a Gatherer (Java 24) for custom intermediate ones.

Further reading

  • Joshua Bloch, Effective Java (3rd edition), chapter 7, items 45 to 48, on using streams judiciously, side effects, returning collections and parallel streams
  • Brian Goetz, “Java Streams” series on IBM developerWorks, and the java.util.stream package documentation, which is unusually thorough
  • Raoul-Gabriel Urma, Mario Fusco and Alan Mycroft, Modern Java in Action (Manning), chapters 4 to 7
  • Doug Lea, “When to use parallel streams”, with the N × Q guideline
  • JEP 485, “Stream Gatherers”, and the java.util.stream.Gatherers documentation
  • The source of java.util.stream.AbstractPipeline and ReferencePipeline in OpenJDK, where copyInto and wrapSink show the sink chain directly