Java Streams Explained: From Loops to Stream Pipelines
Why Java streams exist and how they differ from collections and loops: the "what, not how" style, lazy evaluation, the three stages of a pipeline (source, intermediate, terminal), single-use streams and a first look at parallel streams.
kvi5hnuCode Sprout team member11 min readOn this page
Welcome to the second Core Java course. The first course covered the language itself: classes, interfaces, generics, collections, concurrency and modules. This course covers the libraries that professional Java code is built on: streams, files, regular expressions, XML, networking, databases, date and time, internationalization, security, desktop user interfaces and the Foreign Function and Memory API.
We start with the stream library (java.util.stream), which Java 8 introduced and which has kept growing ever since. Java 24 added gatherers, for example. A stream lets you describe a computation over a sequence of values at a higher level than a loop. You say what result you want, and the library decides how to compute it.
A loop and a stream, side by side
Suppose you have a piece of text and want to know how many of its words are long, say longer than seven letters. First split the text into words. The regular expression \PL+ means "one or more characters that are not letters" (Part 2 explains regular expressions in detail):
String[] words = text.split("\\PL+");
The classic solution is a loop:
int count = 0;
for (String w : words) {
if (w.length() > 7) count++;
}
Here is the same computation as a stream:
long count = Stream.of(words)
.filter(w -> w.length() > 7)
.count();
The stream version reads like the problem statement: take the words, keep the long ones, count them. In the loop you have to read the body to discover that it filters and counts. With a stream, the method names filter and count say it directly.
There's a deeper difference too. The loop spells out the order of every step: start at index 0, test, increment, move on. A stream only describes the result, so the library is free to organize the work. The clearest example: switch stream() to parallelStream() and the filtering and counting are spread over several processor cores, with no other change:
long count = wordList.parallelStream()
.filter(w -> w.length() > 7)
.count();
This is the "what, not how" principle. The loop forgoes any chance of optimization because it dictates exactly how to compute. The stream leaves the scheduling to the implementation, as long as the result is correct.
How a stream differs from a collection
A stream looks a bit like a collection, since both give you a sequence of elements to transform and retrieve. But they are fundamentally different things:
- A stream doesn't store its elements. The elements live in some source, such as a collection, an array or a file, or they are generated on demand. A stream is a view through which they flow.
- Stream operations don't change the source.
filterdoesn't remove anything from the list. It produces a new stream that simply doesn't contain the rejected elements. - Stream operations are lazy wherever possible. Nothing is computed until a result is actually needed. If you ask for the first five long words, the filtering stops after the fifth match. Laziness is also what makes infinite streams possible.
- A stream can be traversed only once. After a terminal operation has run, the stream is used up. Calling another operation on it throws
IllegalStateException. If you need the data twice, create a new stream from the source, or collect the results into a list first.
The three stages of a pipeline
Almost every stream computation has the same shape:
- Create a stream from a source:
list.stream(),Stream.of(...), and the many other ways that the next article covers. - Transform it with zero or more intermediate operations, such as
filter,mapandsorted. Each one returns a new stream, so you can chain them. - Finish with exactly one terminal operation, such as
count,toList,forEachorfindFirst. It produces a result (or a side effect) and forces the lazy operations before it to actually run. Afterward the stream can't be used again.

In the word-counting example, Stream.of(words) creates the stream, filter transforms it, and count is the terminal operation.
What "lazy" really means
When you call filter or map, the stream merely records the operation. When the terminal operation starts, it pulls elements from the source one at a time and pushes each one through the whole chain before reading the next. This is often called vertical processing. The library does not run filter over all elements, then map over all survivors. It takes the first element through filter, then map, then the terminal operation, then the second element, and so on.
That has two consequences you can see in the demo below:
- Building a pipeline with
filterandmapprints nothing. The lambdas run only oncetoList()is called. - With
limit(2), the pipeline stops as soon as two elements have made it to the end. The remaining words,efficientandindeed, are never even looked at. Operations that can finish early like this are called short-circuiting.
Laziness is also why Stream.iterate(1, n -> n + 1), which describes all positive integers, is perfectly usable. As long as something like limit or findFirst ends the pipeline, only the needed elements are ever produced.
Streams or loops?
Streams don't make loops obsolete. A few guidelines:
- Streams shine for data transformations: filtering, mapping, grouping, summing, joining. They're usually shorter and harder to get wrong than the equivalent loops, and they are easy to parallelize.
- Loops are still the better choice when you need to break out early in complicated ways, modify several local variables, handle checked exceptions (lambdas in streams can't throw them without wrapping), or index into several arrays at once.
- Performance is usually similar. For tiny collections a plain loop can be a little faster, because a stream sets up several objects. Measure before you optimize, and don't rewrite clear code for nanoseconds.
- Debugging a long pipeline is a little harder than stepping through a loop, although IntelliJ IDEA and Eclipse have stream debuggers that show each stage's elements.
A complete example
The demo counts the long words of a short passage three ways: with a loop, a stream and a parallel stream. It then shows that the source list is unchanged, makes laziness visible with print statements, demonstrates that a stream can be used only once, and pulls five values out of an infinite stream.
import java.util.*;
import java.util.stream.*;
public class Solution {
static final String TEXT = """
Alice was beginning to get very tired of sitting by her sister on the
bank, and of having nothing to do: once or twice she had peeped into
the book her sister was reading, but it had no pictures or conversations
in it, and what is the use of a book, thought Alice, without pictures or
conversations? So she was considering in her own mind (as well as she
could, for the hot day made her feel very sleepy and stupid), whether
the pleasure of making a daisy-chain would be worth the trouble of
getting up and picking the daisies, when suddenly a White Rabbit with
pink eyes ran close by her.
""";
public static void main(String[] args) {
String[] words = TEXT.split("\\PL+");
List<String> wordList = List.of(words);
// 1. the loop: how to count
int loopCount = 0;
for (String w : words) {
if (w.length() > 7) loopCount++;
}
System.out.println("loop count: " + loopCount);
// 2. the stream: what to count
long streamCount = Stream.of(words).filter(w -> w.length() > 7).count();
System.out.println("stream count: " + streamCount);
// 3. the same pipeline, in parallel
long parallelCount = wordList.parallelStream().filter(w -> w.length() > 7).count();
System.out.println("parallel count: " + parallelCount);
// the long words themselves, collected into a list
List<String> longWords = wordList.stream().filter(w -> w.length() > 7).toList();
System.out.println("long words: " + longWords);
// the source is not modified
System.out.println("source size: " + wordList.size() + " words");
// laziness: nothing runs until the terminal operation
System.out.println("-- building a pipeline");
List<String> sample = List.of("a", "stream", "is", "lazy", "and", "remarkably", "efficient", "indeed");
Stream<String> pipeline = sample.stream()
.filter(w -> {
System.out.println(" filter sees " + w);
return w.length() > 5;
})
.map(w -> {
System.out.println(" map gets " + w);
return w.toUpperCase();
});
System.out.println("-- pipeline built, nothing printed yet");
List<String> firstTwo = pipeline.limit(2).toList();
System.out.println("-- result " + firstTwo);
// a stream can be used only once
Stream<String> once = wordList.stream();
System.out.println("first use: " + once.count());
try {
once.count();
} catch (IllegalStateException e) {
System.out.println("second use: IllegalStateException: " + e.getMessage());
}
// infinite source, finite result thanks to laziness
List<Integer> squares = Stream.iterate(1, n -> n + 1)
.map(n -> n * n)
.filter(n -> n % 2 == 1)
.limit(5)
.toList();
System.out.println("first odd squares: " + squares);
}
}
loop count: 8
stream count: 8
parallel count: 8
long words: [beginning, pictures, conversations, pictures, conversations, considering, pleasure, suddenly]
source size: 113 words
-- building a pipeline
-- pipeline built, nothing printed yet
filter sees a
filter sees stream
map gets stream
filter sees is
filter sees lazy
filter sees and
filter sees remarkably
map gets remarkably
-- result [STREAM, REMARKABLY]
first use: 113
second use: IllegalStateException: stream has already been operated upon or closed
first odd squares: [1, 9, 25, 49, 81]
The parallel count matches the sequential count. count doesn't care about order, so splitting the work across threads can't change the result. Part 1's last article explains when parallel streams pay off and when they don't.
Common questions
Does list.stream() copy the list?
No. The stream reads directly from the list while the terminal operation runs, so creating a stream is cheap even for a huge collection. That is also why the source must not be modified while the pipeline is running (next article).
Can I keep a stream in a field and reuse it?
No, a stream is single-use. Keep the source instead (the list), or a Supplier<Stream<T>> such as () -> words.stream().filter(w -> w.length() > 7), and call get() each time you need a fresh pipeline.
Can a stream contain null?
Yes. Stream.of("a", null) and toList() both accept null. Some operations do not: sorted() with natural ordering throws NullPointerException, and so do findFirst, findAny, min and max when the element they would return is null, because an Optional cannot hold null. Filter nulls out early with filter(Objects::nonNull) if your data may contain them.
Do streams keep the order of my list?
A stream from an ordered source (a List, an array, Stream.of, a sorted set) is ordered, and operations like filter, map, toList and findFirst respect that order, even in parallel. A stream from a HashSet has no defined order. Article 17 explains how ordering interacts with parallel streams.
Is forEach on a stream the same as a for-each loop?
For a sequential stream the effect is the same, but forEach is meant for a final side effect at the end of a pipeline, not as a general loop replacement. If you only want to iterate a collection, for (var w : words) or words.forEach(...) is simpler. For parallel streams, forEach does not even guarantee the order; forEachOrdered does.
Which Java version do I need?
Streams arrived in Java 8. Later versions added methods covered in this part: takeWhile, dropWhile, ofNullable and three-argument iterate (Java 9), toList (Java 16), mapMulti (Java 16) and gatherers (Java 24). The examples in this course run on Java 25.
API reference
java.util.stream.Stream<T> (Java 8)
| Method | Description |
|---|---|
Stream<T> filter(Predicate<? super T> predicate) | a stream of the elements that satisfy predicate (intermediate, lazy) |
<R> Stream<R> map(Function<? super T, ? extends R> mapper) | a stream of mapper applied to each element (intermediate, lazy) |
Stream<T> limit(long maxSize) | at most the first maxSize elements (intermediate, short-circuiting) |
long count() | the number of elements (terminal) |
List<T> toList() (Java 16) | an unmodifiable list of the elements (terminal) |
static <T> Stream<T> iterate(T seed, UnaryOperator<T> f) | the infinite stream seed, f(seed), f(f(seed)), … |
java.util.Collection<E>
| Method | Description |
|---|---|
default Stream<E> stream() (Java 8) | a sequential stream of this collection's elements |
default Stream<E> parallelStream() (Java 8) | a possibly parallel stream of this collection's elements |
Summary
- A stream describes what to compute over a sequence of values. The library decides how, which allows optimizations such as parallel execution.
- Streams don't store elements and don't modify their source. They're lazy, and each stream can be traversed only once.
- A pipeline has three stages: create a stream, apply lazy intermediate operations, then run one terminal operation that produces the result.
- Elements flow through the pipeline one at a time. Short-circuiting operations like
limitstop early, which makes infinite streams usable. - Functions passed to stream operations should be free of side effects. Loops remain a good tool for control-flow-heavy code and checked exceptions.
Practice Questions
What does this code print, and why? Stream<String> s = List.of("a", "b").stream().filter(x -> { System.out.println(x); return true; });
Nothing. filter is an intermediate operation and only records the predicate. Without a terminal operation such as count() or toList(), the pipeline never runs, so the lambda is never called.
After words.stream().filter(w -> w.length() > 7).count(), does the list words still contain the short words?
Yes. Stream operations never modify their source. filter produces a new stream without the short words, and count consumes that stream. The list itself is unchanged.
You store a stream in a variable, call count() on it, then call toList() on the same variable. What happens?
The second call throws IllegalStateException: stream has already been operated upon or closed. A stream can be traversed only once. Create a fresh stream from the source for each pipeline, or collect the elements into a list and reuse the list.
Why can Stream.iterate(1, n -> n + 1).filter(n -> n % 7 == 0).limit(3).toList() finish even though the source is infinite?
Because streams are lazy and process elements one at a time. limit(3) is short-circuiting: as soon as three multiples of 7 (7, 14, 21) have passed through, the terminal operation stops pulling elements, so only 21 elements are ever generated.
Name two situations in which a plain loop is a better fit than a stream.
For example: when the loop body must throw checked exceptions, when you need complex early exits with break or return from the enclosing method, when several local variables are updated in each iteration, or when you iterate over several arrays by index at the same time.
Next: Creating Java Streams: of, generate, iterate, ofNullable and More
Related reading
- Java Reflection and Generics: Class<T>, Type Tokens and the Type Interface
- Java Generics Inheritance Rules and Wildcards: extends, super and ?
- Java Generics: Generic Classes and Generic Methods
- Throwing Exceptions and Creating Custom Exception Classes in Java
- Java Local, Anonymous and Static Nested Classes

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.