Advanced streams

A stream pipeline is a description of work that runs only when a terminal operation pulls elements through it, one at a time. Knowing that explains most of what streams do, including the surprises. This page traces elements through a pipeline, runs the operations added from Java 9 to 16, builds advanced and custom collectors, looks at the spliterator flags that let streams skip work, runs five common traps, and measures streams against a plain loop.

Contents

How a stream pipeline runs

A stream (Java 8) has three parts: a source such as a collection or a range, any number of intermediate operations such as filter and map, and one terminal operation such as toList, count or findFirst. Intermediate operations only record a stage; nothing happens until the terminal operation starts. Then the source's Spliterator pushes elements one at a time through all stages, so each element is filtered, mapped and collected before the next one is read. There are no intermediate lists.

Two properties follow from this design. Operations can short-circuit: findFirst, anyMatch and limit stop pulling as soon as they have their answer, which is also what makes infinite streams usable. And some operations are stateful barriers: sorted must see every element before it can emit the first, and distinct must remember what it has seen.

Stream features added after Java 8
FeatureSinceWhat it doesBest for
takeWhile, dropWhileJava 9Keep or skip elements until a test first failsSorted or time-ordered data
Stream.iterate(seed, hasNext, next), ofNullableJava 9A finite iterate; a stream of zero or one elementLoop-like sequences, optional values
Collectors.filtering, flatMappingJava 9Filter or flatten inside a downstream collectorPer-group processing in groupingBy
Collectors.teeingJava 12Two collectors over one pass, results mergedTwo aggregates at once
mapMulti, Stream.toList()Java 16Emit any number of results per element; collect to an unmodifiable listFlattening without inner streams; the usual end of a pipeline
Gatherers (Stream.gather)Java 24Custom intermediate operationsWindows, scans, stateful steps; see gatherers

Basic operations such as groupingBy are covered on the streams and groupingBy pages. The programs here ran on JDK 21.

Watching elements flow through a pipeline

Each stage prints when it handles an element, so the order of the printed lines shows how the stream really runs. The word list includes short and long words so that filter rejects some of them.

Java
import java.util.List;
import java.util.stream.Stream;

public class Laziness {

    public static void main(String[] args) {
        List<String> words = List.of("apple", "banana", "cherry", "date", "elderberry", "fig");

        // Building the pipeline runs nothing
        Stream<String> pipeline = words.stream()
                .filter(w -> {
                    System.out.println("  filter " + w);
                    return w.length() > 4;
                })
                .map(w -> {
                    System.out.println("  map    " + w);
                    return w.toUpperCase();
                });
        System.out.println("pipeline built, nothing printed yet");

        // The terminal operation pulls elements one at a time, through all stages
        System.out.println("findFirst -> " + pipeline.findFirst().orElse("-"));

        // limit short-circuits: only as many elements as needed are processed
        System.out.println("limit(2):");
        List<String> two = words.stream()
                .peek(w -> System.out.println("  saw " + w))
                .filter(w -> w.contains("e"))
                .limit(2)
                .toList();
        System.out.println("  result " + two);

        // sorted is a barrier: it must see every element before passing any on
        System.out.println("sorted then findFirst:");
        String first = words.stream()
                .peek(w -> System.out.println("  saw " + w))
                .sorted()
                .findFirst()
                .orElse("-");
        System.out.println("  result " + first);
    }
}

Output:

Output
pipeline built, nothing printed yet
  filter apple
  map    apple
findFirst -> APPLE
limit(2):
  saw apple
  saw banana
  saw cherry
  result [apple, cherry]
sorted then findFirst:
  saw apple
  saw banana
  saw cherry
  saw date
  saw elderberry
  saw fig
  result apple
  • Building the pipeline printed nothing. Only findFirst started it, and it stopped after the first element: "apple" passed the filter, was mapped, and was the answer. The other five words were never read.
  • Filter and map alternate per element ("filter apple", "map apple") rather than filtering everything first. This is vertical processing, one element at a time through all stages.
  • With limit(2), the stream read apple (kept), banana (no "e"), cherry (kept), and stopped: three elements read to produce two results. "date", "elderberry" and "fig" were never touched.
  • sorted() before findFirst had to read all six words, because the smallest one could be anywhere. Placing short-circuiting and filtering operations before barriers saves work; on an infinite stream, a barrier before the short-circuit never finishes.

Operations added in Java 9 to 16

A list of sensor readings that rises and then drops shows the difference between takeWhile and filter, and a few orders, one with no items, exercise mapMulti.

Java
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class NewerOperations {

    record Order(String id, List<String> items) { }

    public static void main(String[] args) {
        List<Integer> readings = List.of(3, 5, 8, 13, 2, 21, 1);

        // takeWhile / dropWhile (Java 9): stop or start at the first element that fails
        System.out.println("takeWhile < 10: " + readings.stream().takeWhile(n -> n < 10).toList());
        System.out.println("dropWhile < 10: " + readings.stream().dropWhile(n -> n < 10).toList());
        System.out.println("filter    < 10: " + readings.stream().filter(n -> n < 10).toList());

        // iterate with a condition (Java 9): like a for loop
        System.out.println("iterate powers of 2 below 100: "
                + Stream.iterate(1, n -> n < 100, n -> n * 2).toList());

        // ofNullable (Java 9): zero or one element
        Map<String, String> config = Map.of("host", "db1");
        System.out.println("ofNullable count for host/port: "
                + Stream.ofNullable(config.get("host")).count() + "/"
                + Stream.ofNullable(config.get("port")).count());

        // mapMulti (Java 16): emit any number of results per element, without a stream per element
        List<Order> orders = List.of(new Order("o1", List.of("pen", "ink")),
                new Order("o2", List.of()), new Order("o3", List.of("pad")));
        List<String> lines = orders.stream()
                .<String>mapMulti((o, out) -> {
                    for (String item : o.items()) {
                        out.accept(o.id() + ":" + item);
                    }
                })
                .toList();
        System.out.println("mapMulti: " + lines);

        // toList() (Java 16) is unmodifiable; Collectors.toList() makes no such promise
        List<Integer> unmodifiable = IntStream.range(0, 3).boxed().toList();
        List<Integer> mutable = IntStream.range(0, 3).boxed().collect(Collectors.toList());
        mutable.add(3);
        System.out.println("Collectors.toList() after add: " + mutable);
        try {
            unmodifiable.add(3);
        } catch (UnsupportedOperationException e) {
            System.out.println("Stream.toList().add: UnsupportedOperationException");
        }
    }
}

Output:

Output
takeWhile < 10: [3, 5, 8]
dropWhile < 10: [13, 2, 21, 1]
filter    < 10: [3, 5, 8, 2, 1]
iterate powers of 2 below 100: [1, 2, 4, 8, 16, 32, 64]
ofNullable count for host/port: 1/0
mapMulti: [o1:pen, o1:ink, o3:pad]
Collectors.toList() after add: [0, 1, 2, 3]
Stream.toList().add: UnsupportedOperationException
  • takeWhile(n -> n < 10) stopped at 13, the first failure, and never looked at the 2 and 1 after it; filter kept them. dropWhile is the complement, starting at 13 and keeping everything after it. On an unordered source, such as a HashSet, which elements count as "first" is undefined.
  • The three-argument Stream.iterate works like a for loop: seed 1, continue while below 100, double each time.
  • Stream.ofNullable gave one element for the existing key and none for the missing one, which is handy inside flatMap.
  • mapMulti pushed one line per item into the consumer and nothing for the empty order. It does the job of flatMap without creating a small stream per element, which is cheaper when most elements produce zero or one result.
  • Stream.toList() returns an unmodifiable list, so add threw UnsupportedOperationException. Collectors.toList() returned an ArrayList here, but its Javadoc promises nothing about mutability. Use Collectors.toCollection(ArrayList::new) when you need a list you can change.

Advanced collectors: teeing, filtering, flatMapping

Five transactions over three accounts are enough to show each collector, and account A has no transaction over 200, which is exactly the case where filtering and filter differ.

Java
import java.util.DoubleSummaryStatistics;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.stream.Collectors;

public class TeeingAndMore {

    record Txn(String account, String type, double amount, Set<String> tags) {
    }

    public static void main(String[] args) {
        List<Txn> txns = List.of(
                new Txn("A", "debit", 120.0, Set.of("food")),
                new Txn("B", "credit", 900.0, Set.of("salary")),
                new Txn("A", "debit", 45.5, Set.of("food", "travel")),
                new Txn("C", "debit", 300.0, Set.of("rent")),
                new Txn("B", "debit", 60.0, Set.of("travel")));

        // teeing (Java 12): two collectors over one pass, then merge their results
        record MinMax(double min, double max) {
        }
        MinMax range = txns.stream().collect(Collectors.teeing(
                Collectors.minBy((a, b) -> Double.compare(a.amount(), b.amount())),
                Collectors.maxBy((a, b) -> Double.compare(a.amount(), b.amount())),
                (lo, hi) -> new MinMax(lo.orElseThrow().amount(), hi.orElseThrow().amount())));
        System.out.println("teeing min/max: " + range);

        double share = txns.stream().collect(Collectors.teeing(
                Collectors.filtering(t -> t.type().equals("debit"),
                        Collectors.summingDouble(Txn::amount)),
                Collectors.summingDouble(Txn::amount),
                (debits, all) -> debits / all * 100));
        System.out.printf("debits are %.1f%% of all volume%n", share);

        // filtering (Java 9): keeps groups that end up empty, unlike filter() before grouping
        Map<String, Long> bigByAccount = txns.stream().collect(Collectors.groupingBy(
                Txn::account, TreeMap::new,
                Collectors.filtering(t -> t.amount() > 200, Collectors.counting())));
        System.out.println("txns over 200 per account (filtering): " + bigByAccount);
        Map<String, Long> withFilterFirst = txns.stream().filter(t -> t.amount() > 200)
                .collect(Collectors.groupingBy(Txn::account, TreeMap::new, Collectors.counting()));
        System.out.println("same with filter() first:              " + withFilterFirst);

        // flatMapping (Java 9): flatten a collection per element inside a group
        Map<String, Set<String>> tagsByAccount = txns.stream().collect(Collectors.groupingBy(
                Txn::account, TreeMap::new,
                Collectors.flatMapping(t -> t.tags().stream(),
                        Collectors.toCollection(TreeSet::new))));
        System.out.println("tags per account: " + tagsByAccount);

        // summarizing: count, sum, min, average, max at once
        DoubleSummaryStatistics stats = txns.stream()
                .collect(Collectors.summarizingDouble(Txn::amount));
        System.out.printf("stats: n=%d sum=%.1f avg=%.2f%n", stats.getCount(), stats.getSum(),
                stats.getAverage());
    }
}

Output:

Output
teeing min/max: MinMax[min=45.5, max=900.0]
debits are 36.9% of all volume
txns over 200 per account (filtering): {A=0, B=1, C=1}
same with filter() first:              {B=1, C=1}
tags per account: {A=[food, travel], B=[salary, travel], C=[rent]}
stats: n=5 sum=1425.5 avg=285.10
  • teeing sent every element to two collectors, minBy and maxBy, and merged their results into a record, in one pass over the data. The second use divided the debit sum (525.5) by the total (1,425.5): 36.9%.
  • Collectors.filtering inside groupingBy kept account A with a count of 0. Filtering before grouping removed A completely, because no element of A reached the collector. When reports must show every group, filter downstream.
  • flatMapping flattened each transaction's tag set into one sorted set per account.
  • summarizingDouble computed count, sum, minimum, average and maximum together, here 5 transactions with an average of 285.10.

Writing a custom Collector

A collector is four functions: a supplier that creates a mutable container, an accumulator that adds one element, a combiner that merges two containers from parallel parts, and an optional finisher that turns the container into the result. The first collector wraps words into lines of at most 20 characters; the second computes a maximum with 0 for an empty stream.

Java
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collector;
import java.util.stream.IntStream;

public class CustomCollector {

    // Collects strings into lines no longer than 'width', like word wrapping
    static Collector<String, List<StringBuilder>, List<String>> wrap(int width) {
        return Collector.of(
                ArrayList::new,                                     // supplier: new container
                (lines, word) -> {                                  // accumulator: add one element
                    if (lines.isEmpty()
                            || lines.get(lines.size() - 1).length() + 1 + word.length() > width) {
                        lines.add(new StringBuilder(word));
                    } else {
                        lines.get(lines.size() - 1).append(' ').append(word);
                    }
                },
                (left, right) -> {                                  // combiner: merge two partials
                    left.addAll(right);
                    return left;
                },
                lines -> lines.stream().map(StringBuilder::toString).toList()); // finisher
    }

    // A simpler custom collector: running max with Collector.of and an int[] holder
    static Collector<Integer, int[], Integer> maxOrZero() {
        return Collector.of(
                () -> new int[] {0},
                (box, n) -> box[0] = Math.max(box[0], n),
                (a, b) -> {
                    a[0] = Math.max(a[0], b[0]);
                    return a;
                },
                box -> box[0]);
    }

    public static void main(String[] args) {
        String text = "the quick brown fox jumps over the lazy dog and keeps on running";
        List<String> wrapped = List.of(text.split(" ")).stream().collect(wrap(20));
        wrapped.forEach(line -> System.out.println("|" + line + "|"));

        int max = IntStream.rangeClosed(1, 100).boxed().parallel().collect(maxOrZero());
        System.out.println("max of 1..100 (parallel): " + max);
        int empty = List.<Integer>of().stream().collect(maxOrZero());
        System.out.println("max of empty stream: " + empty);
    }
}

Output:

Output
|the quick brown fox|
|jumps over the lazy|
|dog and keeps on|
|running|
max of 1..100 (parallel): 100
max of empty stream: 0
  • The words were packed into lines of up to 20 characters. The container is a list of StringBuilders, and the finisher converts them to strings, so callers never see the mutable state.
  • The maximum collector ran on a parallel stream and gave 100. Each worker accumulated into its own int[] holder, and the combiner merged the holders. An empty stream returned 0 from the supplier's initial value.
  • The combiner of the wrapping collector only concatenates line lists, so in a parallel stream two half-full lines could meet at a chunk boundary without being joined. A combiner must give the same result as sequential accumulation; this one is correct only for sequential streams, which is worth stating in its documentation.
  • Collector.of also takes characteristics such as UNORDERED and IDENTITY_FINISH that let the stream skip work.

Spliterator characteristics: how streams skip work

Every stream starts from a Spliterator, which can split itself for parallel processing and reports characteristics about its elements. The stream uses those flags to optimize. The program prints them for common sources and shows one optimization in action.

Java
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Spliterator;
import java.util.TreeSet;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class Characteristics {

    static String flags(Spliterator<?> s) {
        Map<String, Integer> all = new LinkedHashMap<>();
        all.put("ORDERED", Spliterator.ORDERED);
        all.put("DISTINCT", Spliterator.DISTINCT);
        all.put("SORTED", Spliterator.SORTED);
        all.put("SIZED", Spliterator.SIZED);
        all.put("SUBSIZED", Spliterator.SUBSIZED);
        all.put("NONNULL", Spliterator.NONNULL);
        all.put("IMMUTABLE", Spliterator.IMMUTABLE);
        List<String> on = new ArrayList<>();
        all.forEach((name, bit) -> {
            if (s.hasCharacteristics(bit)) {
                on.add(name);
            }
        });
        return on + ", estimateSize " + s.estimateSize();
    }

    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>(List.of(5, 3, 8));
        Set<Integer> hash = new HashSet<>(list);
        Set<Integer> tree = new TreeSet<>(list);
        System.out.println("ArrayList:          " + flags(list.spliterator()));
        System.out.println("List.of:            " + flags(List.of(5, 3, 8).spliterator()));
        System.out.println("HashSet:            " + flags(hash.spliterator()));
        System.out.println("TreeSet:            " + flags(tree.spliterator()));
        System.out.println("IntStream.range:    " + flags(IntStream.range(0, 1000).spliterator()));
        System.out.println("after filter:       "
                + flags(list.stream().filter(n -> n > 4).spliterator()));
        System.out.println("Stream.iterate:     "
                + flags(Stream.iterate(1, n -> n + 1).spliterator()));

        // SIZED lets count() skip the pipeline entirely (Java 9 and later)
        int[] peeked = new int[1];
        long count = list.stream().peek(n -> peeked[0]++).count();
        System.out.println("count() = " + count + ", peek ran " + peeked[0] + " times");
        long filteredCount = list.stream().peek(n -> peeked[0]++).filter(n -> n > 4).count();
        System.out.println("with filter: count() = " + filteredCount + ", peek total now "
                + peeked[0]);
    }
}

Output:

Output
ArrayList:          [ORDERED, SIZED, SUBSIZED], estimateSize 3
List.of:            [ORDERED, SIZED, SUBSIZED], estimateSize 3
HashSet:            [DISTINCT, SIZED], estimateSize 3
TreeSet:            [ORDERED, DISTINCT, SORTED, SIZED], estimateSize 3
IntStream.range:    [ORDERED, DISTINCT, SORTED, SIZED, SUBSIZED, NONNULL, IMMUTABLE], estimateSize 1000
after filter:       [ORDERED], estimateSize 3
Stream.iterate:     [ORDERED, IMMUTABLE], estimateSize 9223372036854775807
count() = 3, peek ran 0 times
with filter: count() = 2, peek total now 3
  • A list is ORDERED and SIZED; a HashSet is DISTINCT but not ordered; a TreeSet is also SORTED, so sorted() on it with natural order does nothing and distinct() on any set is free. IntStream.range has every flag, including SUBSIZED, which means it splits into exactly known halves, ideal for parallel work.
  • After filter, the stream is no longer SIZED: the estimate of 3 is just an upper bound. An infinite iterate reports Long.MAX_VALUE as its size.
  • Because the list is SIZED, count() returned 3 without running the pipeline: peek ran 0 times. Since Java 9, the count Javadoc allows this. With a filter in the way the size is unknown, so the pipeline ran and peek saw all 3 elements. Never put logic that must run in peek.

Five stream traps

The mistakes below compile without warnings. The race in the second case does not fail every time, so the program repeats it 10 times and reports whether any attempt went wrong.

Java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class StreamTraps {

    public static void main(String[] args) {
        // 1. A stream can be consumed only once
        Stream<String> s = Stream.of("a", "b");
        s.count();
        try {
            s.count();
        } catch (IllegalStateException e) {
            System.out.println("1. reuse: IllegalStateException: " + e.getMessage());
        }

        // 2. Adding to a shared ArrayList from a parallel stream is a data race
        int brokenRuns = 0;
        for (int attempt = 0; attempt < 10; attempt++) {
            List<Integer> unsafe = new ArrayList<>();
            try {
                IntStream.range(0, 100000).parallel().forEach(unsafe::add);
                if (unsafe.size() != 100000) {
                    brokenRuns++;                     // elements lost
                }
            } catch (ArrayIndexOutOfBoundsException e) {
                brokenRuns++;                         // internal array corrupted
            }
        }
        boolean broken = brokenRuns > 0;
        List<Integer> safe = IntStream.range(0, 100000).parallel().boxed().toList();
        System.out.println("2. forEach(list::add) broke in some of 10 runs: " + broken
                + "; toList() size " + safe.size());

        // 3. Parallel forEach ignores encounter order; forEachOrdered keeps it
        List<Integer> order = Collections.synchronizedList(new ArrayList<>());
        IntStream.range(0, 1000).parallel().forEachOrdered(order::add);
        List<Integer> expected = IntStream.range(0, 1000).boxed().toList();
        System.out.println("3. forEachOrdered kept order: " + order.equals(expected));

        // 4. Collectors.toMap throws on duplicate keys unless given a merge function
        List<String> names = List.of("ann", "bob", "amy");
        try {
            names.stream().collect(Collectors.toMap(n -> n.charAt(0), n -> n));
        } catch (IllegalStateException e) {
            System.out.println("4. toMap: " + e.getMessage());
        }
        System.out.println("4. with merge: " + names.stream().collect(
                Collectors.toMap(n -> n.charAt(0), n -> n, (x, y) -> x + "+" + y)));

        // 5. Infinite streams need a short-circuit before any barrier
        List<Integer> firstSquares = Stream.iterate(1, n -> n + 1).map(n -> n * n).limit(5)
                .toList();
        System.out.println("5. limit before collecting an infinite stream: " + firstSquares
                + " (sorted() before limit would never finish)");
    }
}

Output:

Output
1. reuse: IllegalStateException: stream has already been operated upon or closed
2. forEach(list::add) broke in some of 10 runs: true; toList() size 100000
3. forEachOrdered kept order: true
4. toMap: Duplicate key a (attempted merging values ann and amy)
4. with merge: {a=ann+amy, b=bob}
5. limit before collecting an infinite stream: [1, 4, 9, 16, 25] (sorted() before limit would never finish)
  1. A stream is single-use. The second count() threw IllegalStateException. Keep the source, or a Supplier<Stream<T>>, if you need to run the pipeline again.
  2. Adding to a shared ArrayList from a parallel forEach lost elements or threw ArrayIndexOutOfBoundsException in some of the 10 runs. Collecting with toList() gave all 100,000, because each worker fills its own container and the results are combined. Side effects on shared state are the most common parallel stream bug.
  3. A parallel forEach processes elements in whatever order the workers reach them. forEachOrdered kept the encounter order, at the cost of waiting for earlier chunks.
  4. Collectors.toMap threw IllegalStateException for the duplicate key 'a', naming both values. With a merge function as the third argument, the values were combined.
  5. An infinite stream works only if a short-circuiting operation such as limit comes before any barrier. Stream.iterate(1, n -> n + 1).sorted() would run until memory ran out.

Streams versus loops: speed

The same calculation, the sum of the squares of the even values among 20 million numbers, runs as a for loop, an IntStream, a boxed Stream<Integer> and a parallel IntStream. Best of 5 runs; a rough comparison, not a benchmark.

Java
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;

public class StreamVsLoop {

    interface Job {
        long run();
    }

    static long best(Job job) {
        long best = Long.MAX_VALUE;
        for (int i = 0; i < 5; i++) {
            long t0 = System.nanoTime();
            job.run();
            best = Math.min(best, System.nanoTime() - t0);
        }
        return best / 1000000;
    }

    public static void main(String[] args) {
        int n = 20000000;
        List<Integer> boxed = new ArrayList<>(n);
        int[] prims = new int[n];
        for (int i = 0; i < n; i++) {
            boxed.add(i % 1000);
            prims[i] = i % 1000;
        }
        // sum of squares of the even values
        long loop = best(() -> {
            long sum = 0;
            for (int v : prims) {
                if (v % 2 == 0) {
                    sum += (long) v * v;
                }
            }
            return sum;
        });
        long intStream = best(() -> IntStream.of(prims).filter(v -> v % 2 == 0)
                .mapToLong(v -> (long) v * v).sum());
        long boxedStream = best(() -> boxed.stream().filter(v -> v % 2 == 0)
                .map(v -> (long) v * v).reduce(0L, Long::sum));
        long parallel = best(() -> IntStream.of(prims).parallel().filter(v -> v % 2 == 0)
                .mapToLong(v -> (long) v * v).sum());
        System.out.printf("20,000,000 values, best of 5 runs:%n");
        System.out.printf("for loop over int[]          %,4d ms%n", loop);
        System.out.printf("IntStream over int[]         %,4d ms%n", intStream);
        System.out.printf("Stream<Integer> + reduce     %,4d ms%n", boxedStream);
        System.out.printf("parallel IntStream           %,4d ms%n", parallel);
    }
}

Output (2-CPU Linux machine with JDK 21, best of 5):

Output
20,000,000 values, best of 5 runs:
for loop over int[]            43 ms
IntStream over int[]           38 ms
Stream<Integer> + reduce      104 ms
parallel IntStream             19 ms
  • The IntStream was as fast as the loop. Once the JIT inlines the lambdas, the pipeline compiles down to much the same machine code.
  • The boxed Stream<Integer> with reduce was two to three times slower: it reads Integer objects scattered on the heap and creates a Long for every partial sum. Use mapToInt, mapToLong and sum() for numbers.
  • The parallel stream took about half the time of the loop on 2 cores, because an int[] splits evenly and the work per element is uniform. For small inputs, or sources like LinkedList that split badly, parallel is often slower; see Fork/Join.

Choosing stream tools

Which operation or collector to use
NeedUse
A list resulttoList(), or Collectors.toCollection(ArrayList::new) to modify it later
Stop at the first element that fails a testtakeWhile
Zero or more outputs per elementflatMap, or mapMulti when most produce zero or one
Two aggregates in one passCollectors.teeing
Filter but keep empty groupsgroupingBy with Collectors.filtering
A reusable, unusual aggregationCollector.of with a correct combiner
A custom intermediate stepGatherers (Java 24)
Numeric workIntStream, LongStream, DoubleStream
Side effects or complex control flowA plain loop

See Optional for the results of findFirst and max, and functional interfaces for the functions streams take.