Creating Java Streams: of, generate, iterate, ofNullable and More
Every way to get a Java stream: from collections, arrays and values, infinite streams with generate and iterate, ofNullable, String.lines, Pattern, Scanner, Files.lines, Stream.Builder and iterators, plus the noninterference rule and the Stream.of(int[]) trap.
kvi5hnuCode Sprout team member10 min readOn this page
Every stream pipeline begins with a source. The previous article used list.stream() and Stream.of(words). There are many more ways to get a stream, and knowing them saves you from building a temporary list just to stream it. This article tours them all, explains how infinite streams work, shows when a stream must be closed, and ends with the one rule you must never break: don't modify a stream's source while the stream is running.
From collections, arrays and individual values
Collections. Every Collection has stream() and parallelStream(). A Map isn't a collection, but its views are: map.keySet().stream(), map.values().stream() and map.entrySet().stream().
Arrays. The static Stream.of method has a varargs parameter, so you can pass it an array or a list of values:
Stream<String> words = Stream.of(contents.split("\\PL+"));
Stream<String> song = Stream.of("gently", "down", "the", "stream");
To stream only part of an array, use Arrays.stream(array, from, to). As usual, from is inclusive and to is exclusive.
Nothing at all. Stream.empty() makes a stream with no elements. The element type is inferred from the context, so Stream<String> silence = Stream.empty(); is the same as Stream.<String>empty().
Infinite streams: generate and iterate
Two static methods of Stream create streams that never end on their own.
generate takes a function with no parameters, a Supplier<T>, and calls it whenever the stream needs another element:
Stream<String> echos = Stream.generate(() -> "Echo");
Stream<Double> randoms = Stream.generate(Math::random);
iterate takes a seed and a function (a UnaryOperator<T>) that is applied over and over to the previous element:
Stream<BigInteger> integers = Stream.iterate(BigInteger.ZERO, n -> n.add(BigInteger.ONE));
The first element is the seed 0. The second is f(0), which is 1, the third is f(f(0)), which is 2, and so on.
An infinite stream is safe as long as the pipeline eventually stops pulling elements, for example with limit(10), findFirst() or takeWhile(...). An operation that needs all elements, such as the terminal operations count() and toList() or the stateful intermediate operation sorted(), would run forever (or until memory runs out) on an infinite stream.
iterate with a stop condition
Since Java 9, iterate has a three-argument form that ends the stream as soon as an element fails a predicate. It reads just like a for loop:
var limit = new BigInteger("10000000");
Stream<BigInteger> integers = Stream.iterate(BigInteger.ZERO,
n -> n.compareTo(limit) < 0, // like the loop condition
n -> n.add(BigInteger.ONE)); // like the increment
Compare for (int n = 1; n <= 100; n *= 3) with Stream.iterate(1, n -> n <= 100, n -> n * 3), which yields 1, 3, 9, 27, 81. The seed itself is tested too, so if the seed already fails the predicate, the stream is empty.
Zero or one element: ofNullable
Stream.ofNullable(x) (Java 9) returns an empty stream if x is null, and a one-element stream otherwise. On its own it looks pointless, but inside flatMap it's a neat way to drop null results, as you'll see in the articles on flatMap and Optional.
Streams from the Java API
More and more JDK methods hand out streams directly:
| Source | Stream of |
|---|---|
string.lines() (Java 11) | the lines of a string, without line terminators |
string.chars(), string.codePoints() | the characters as an IntStream |
Pattern.compile(regex).splitAsStream(text) | the parts of text between matches |
pattern.matcher(text).results() (Java 9) | every match, as MatchResult objects |
new Scanner(text).tokens() (Java 9) | the whitespace-separated tokens |
Files.lines(path), bufferedReader.lines() | the lines of a file or reader |
Files.list(dir), Files.walk(dir) | directory entries (Part 2) |
random.ints(), random.doubles() | random numbers as primitive streams |
optional.stream() (Java 9) | zero or one element |
Locale.availableLocales() (Java 21) | all installed locales |
bitSet.stream() | the indexes of set bits |
Note how splitAsStream and Scanner.tokens() split differently. The regex \PL+ treats any run of non-letters as a separator, so punctuation disappears. The scanner splits only at whitespace, so "Row," keeps its comma.
Streams that must be closed
Most streams don't hold any resources, and you never close them. Streams that read from files are different. Files.lines keeps the file open until the stream is closed, so always use try-with-resources:
try (Stream<String> lines = Files.lines(path)) {
process lines
}
Stream implements AutoCloseable, and closing it runs any handlers registered with onClose. A terminal operation does not close the stream, so without try-with-resources the file stays open until the garbage collector happens to clean up. That leaks file handles in long-running programs, and on Windows it can stop you from deleting the file.
Building a stream element by element
If you produce the elements yourself in a loop, you could add them to a list and call stream(). A Stream.Builder is slightly more efficient because it doesn't have to support anything but adding:
static Stream<Integer> digits(int n) {
Stream.Builder<Integer> builder = Stream.builder();
while (n != 0) {
builder.add(n % 10);
n = n / 10;
}
return builder.build();
}
After build(), you can't add more elements. Trying to throws IllegalStateException.
From an Iterator or a plain Iterable
Some APIs give you only an Iterator, or an Iterable that isn't a Collection (a Path is iterable over its name components, for example). Neither has a stream() method. Bridging them requires a spliterator, the stream library's internal iteration abstraction. A spliterator is like an iterator that can also split itself into parts, which is what makes parallel processing possible (article 17).
// from an Iterable that isn't a Collection
Stream<Path> parts = StreamSupport.stream(path.spliterator(), false);
// from an Iterator
Stream<T> stream = StreamSupport.stream(
Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false);
The false argument asks for a sequential stream. Spliterator.ORDERED declares that the elements have a meaningful order, which operations like limit and findFirst respect.
Noninterference: don't change the source mid-stream
A stream doesn't copy its data. It reads from the source while the terminal operation runs. If you modify the source collection during that time, the result is undefined: the stream may skip elements, see some twice, throw ConcurrentModificationException, or fail in stranger ways. The documentation calls the rule noninterference.
Because intermediate operations are lazy, the source may change before the terminal operation starts. This works, although it's confusing and not recommended:
Stream<String> words = wordList.stream();
wordList.add("END"); // the pipeline hasn't run yet
long n = words.distinct().count(); // sees "END"
This is wrong:
wordList.stream().forEach(s -> { if (s.length() < 12) wordList.remove(s); }); // ERROR: interference
In the demo, a similar removal makes ArrayList's spliterator read past the shrunken list and hand a null to the lambda, which fails with a NullPointerException. That's a good illustration of "undefined". To remove elements, use wordList.removeIf(s -> s.length() < 12), or build a new list with filter(...).toList().
A complete example
The show helper prints at most six elements of any stream, so it works for infinite streams too. The random numbers come from a Random with a fixed seed, so the output is the same on every run.
import java.io.IOException;
import java.math.BigInteger;
import java.nio.file.*;
import java.util.*;
import java.util.random.RandomGenerator;
import java.util.regex.Pattern;
import java.util.stream.*;
public class Solution {
public static void main(String[] args) throws IOException {
String contents = "Row, row, row your boat\ngently down the stream.\nMerrily, merrily, merrily,\nlife is but a dream.";
// from arrays and values
show("Stream.of(array)", Stream.of(contents.split("\\PL+")));
show("Stream.of(values)", Stream.of("gently", "down", "the", "stream"));
String[] days = { "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" };
show("Arrays.stream(days, 5, 7)", Arrays.stream(days, 5, 7));
show("Stream.empty()", Stream.<String>empty());
// from collections and maps
List<String> crew = List.of("Ada", "Grace", "Linus");
show("list.stream()", crew.stream());
Map<String, Integer> ages = new TreeMap<>(Map.of("Ada", 36, "Grace", 85, "Linus", 55));
show("map.entrySet().stream()", ages.entrySet().stream());
// infinite streams, truncated by show()
show("generate", Stream.generate(() -> "Echo"));
RandomGenerator random = new Random(42);
show("generate(random)", Stream.generate(() -> random.nextInt(100)));
show("iterate", Stream.iterate(BigInteger.ONE, n -> n.add(BigInteger.ONE)));
show("iterate (doubling)", Stream.iterate(1, n -> n * 2));
// finite iterate: like a for loop
show("iterate with hasNext", Stream.iterate(1, n -> n <= 100, n -> n * 3));
// zero or one element
String present = "here", absent = null;
show("ofNullable(\"here\")", Stream.ofNullable(present));
show("ofNullable(null)", Stream.ofNullable(absent));
// streams from the API
show("lines()", contents.lines());
show("splitAsStream", Pattern.compile("\\PL+").splitAsStream(contents));
try (var scanner = new Scanner(contents)) {
show("Scanner.tokens()", scanner.tokens());
}
show("Pattern.matcher(...).results()",
Pattern.compile("\\p{Lu}\\p{L}*").matcher(contents).results().map(r -> r.group()));
// a file: close the stream with try-with-resources
Path file = Files.createTempFile("song", ".txt");
Files.writeString(file, contents);
try (Stream<String> lines = Files.lines(file)) {
show("Files.lines", lines);
}
Files.delete(file);
// Stream.Builder
show("digits(2025)", digits(2025));
// an Iterator and a non-collection Iterable
Iterator<Path> components = Path.of("usr", "share", "dict", "words").iterator();
show("from Iterator", StreamSupport.stream(
Spliterators.spliteratorUnknownSize(components, Spliterator.ORDERED), false));
Iterable<Path> iterable = Path.of("home", "ada", "notes.txt");
show("from Iterable", StreamSupport.stream(iterable.spliterator(), false));
// the Stream.of(int[]) trap
int[] numbers = { 3, 1, 4, 1, 5 };
System.out.println("Stream.of(int[]) has " + Stream.of(numbers).count() + " element");
System.out.println("Arrays.stream(int[]) has " + Arrays.stream(numbers).count() + " elements");
// noninterference: changing the source before the terminal operation is tolerated
var wordList = new ArrayList<>(List.of("a", "b", "a"));
Stream<String> words = wordList.stream();
wordList.add("END");
System.out.println("distinct after late add: " + words.distinct().count());
// ...but not during it
try {
wordList.stream().forEach(s -> { if (s.equals("b")) wordList.remove(s); });
} catch (RuntimeException e) {
System.out.println("modifying the source during forEach: " + e.getClass().getSimpleName());
}
}
static Stream<Integer> digits(int n) {
Stream.Builder<Integer> builder = Stream.builder();
while (n != 0) {
builder.add(n % 10);
n = n / 10;
}
return builder.build();
}
static <T> void show(String title, Stream<T> stream) {
final int SIZE = 6;
List<T> first = stream.limit(SIZE + 1).toList();
var out = new StringJoiner(" | ", title + ": [", "]");
for (int i = 0; i < first.size(); i++)
out.add(i < SIZE ? String.valueOf(first.get(i)) : "...");
System.out.println(out);
}
}
Stream.of(array): [Row | row | row | your | boat | gently | ...]
Stream.of(values): [gently | down | the | stream]
Arrays.stream(days, 5, 7): [Sat | Sun]
Stream.empty(): []
list.stream(): [Ada | Grace | Linus]
map.entrySet().stream(): [Ada=36 | Grace=85 | Linus=55]
generate: [Echo | Echo | Echo | Echo | Echo | Echo | ...]
generate(random): [30 | 63 | 48 | 84 | 70 | 25 | ...]
iterate: [1 | 2 | 3 | 4 | 5 | 6 | ...]
iterate (doubling): [1 | 2 | 4 | 8 | 16 | 32 | ...]
iterate with hasNext: [1 | 3 | 9 | 27 | 81]
ofNullable("here"): [here]
ofNullable(null): []
lines(): [Row, row, row your boat | gently down the stream. | Merrily, merrily, merrily, | life is but a dream.]
splitAsStream: [Row | row | row | your | boat | gently | ...]
Scanner.tokens(): [Row, | row, | row | your | boat | gently | ...]
Pattern.matcher(...).results(): [Row | Merrily]
Files.lines: [Row, row, row your boat | gently down the stream. | Merrily, merrily, merrily, | life is but a dream.]
digits(2025): [5 | 2 | 0 | 2]
from Iterator: [usr | share | dict | words]
from Iterable: [home | ada | notes.txt]
Stream.of(int[]) has 1 element
Arrays.stream(int[]) has 5 elements
distinct after late add: 3
modifying the source during forEach: NullPointerException
Common questions
What is the difference between Stream.of(x) with a null argument and Stream.ofNullable(x)?
Stream.of((String) null) uses the single-element overload and produces a stream with one element, null. Stream.ofNullable(null) produces an empty stream. Passing a null array to the varargs form, Stream.of((String[]) null), throws NullPointerException.
Can I change the source before the terminal operation runs?
Yes, for well-behaved sources such as ArrayList. They bind to their data late, when the terminal operation starts. A stream created from a list, followed by list.add("b") and then toList(), sees the new element. It works, but it makes code hard to follow, so build the stream right where you use it.
Is Stream.generate ordered?
No, generate produces an unordered stream. Sequentially you still get the elements in the order the supplier produces them. For a parallel stream, limit(n) may then pick any n generated elements, which matters if the supplier has state, such as a counter. Use iterate or IntStream.range when the position matters.
How do I get a stream of a Map's entries sorted by key or value?
map.entrySet().stream().sorted(Map.Entry.comparingByKey()), or comparingByValue(). A TreeMap gives a stream already sorted by key.
Should I close every stream?
Only streams that hold a resource: those from Files.lines, Files.list, Files.walk, Files.find, BufferedReader.lines (close the reader) and Scanner.tokens over a file. Streams over collections, arrays and generators hold nothing, and closing them does no harm, but it is not necessary.
How do I stream the characters of a string?
text.chars() gives IntStream code units and text.codePoints() gives code points. Convert back with mapToObj(Character::toString), which accepts a code point since Java 11. For user-visible characters, use grapheme clusters as shown in the next article.
API reference
java.util.stream.Stream<T>
| Method | Description |
|---|---|
static <T> Stream<T> of(T... values) | a stream of the given values |
static <T> Stream<T> empty() | a stream with no elements |
static <T> Stream<T> generate(Supplier<? extends T> s) | an infinite stream whose elements are produced by calling s |
static <T> Stream<T> iterate(T seed, UnaryOperator<T> f) | the infinite stream seed, f(seed), f(f(seed)), … |
static <T> Stream<T> iterate(T seed, Predicate<? super T> hasNext, UnaryOperator<T> next) (Java 9) | like the above, ending before the first element that fails hasNext |
static <T> Stream<T> ofNullable(T t) (Java 9) | an empty stream if t is null, otherwise a stream containing t |
static <T> Stream.Builder<T> builder() | a builder; call add or accept, then build() |
void close(), Stream<T> onClose(Runnable handler) | closes the stream and runs the close handlers |
Other sources
| Method | Description |
|---|---|
static <T> Stream<T> Arrays.stream(T[] array, int from, int to) | a stream of part of an array (overloads for int[], long[], double[]) |
Stream<String> String.lines() (Java 11) | the lines of the string |
Stream<String> Pattern.splitAsStream(CharSequence input) | the parts of input delimited by the pattern |
Stream<MatchResult> Matcher.results() (Java 9) | all matches |
Stream<String> Scanner.tokens() (Java 9) | the scanner's tokens |
static Stream<String> Files.lines(Path path), lines(Path path, Charset cs) | the lines of a file (UTF-8 by default); must be closed |
static <T> Stream<T> StreamSupport.stream(Spliterator<T> spliterator, boolean parallel) | a stream from a spliterator |
static <T> Spliterator<T> Spliterators.spliteratorUnknownSize(Iterator<? extends T> it, int characteristics) | wraps an iterator |
default Spliterator<T> Iterable.spliterator() | a spliterator for any Iterable |
Summary
- Get streams from collections (
stream()), map views, arrays (Stream.of,Arrays.stream), individual values (Stream.of) or nothing (Stream.empty()). generateand two-argumentiterateproduce infinite streams, so they must be cut short bylimit,takeWhileor a short-circuiting terminal operation. Three-argumentiteratestops by itself, like aforloop.ofNullablemakes a stream of zero or one element. Many JDK methods return streams directly:lines,splitAsStream,results,tokens,Files.linesand more.- Close streams backed by files with try-with-resources.
- Use
Stream.Builderto assemble elements, andStreamSupportwith spliterators to stream anIteratoror a non-collectionIterable. - Never modify a stream's source while its terminal operation runs.
Practice Questions
What is the type of Stream.of(new int[] {1, 2, 3}), and how many elements does it have?
It's a Stream<int[]> with one element, the array itself, because type parameters can't be primitive types. Use Arrays.stream(new int[] {1, 2, 3}) or IntStream.of(1, 2, 3) to get an IntStream with three elements.
Write a stream of the powers of 2 that are less than 1,000, without using limit.
Stream.iterate(1, n -> n < 1000, n -> n * 2). The three-argument iterate ends before the first element that fails the predicate, so the stream is 1, 2, 4, …, 512.
Why should Files.lines(path) be used in a try-with-resources statement, while list.stream() is never closed?
Files.lines keeps the file open while the stream is in use and releases it only when the stream is closed. Terminal operations don't close streams. A stream over a list holds no external resource, so there is nothing to release.
What is the difference between Stream.generate(supplier) and Stream.iterate(seed, f)?
generate calls the supplier independently for every element, so elements don't depend on each other (constants, random numbers). iterate computes each element from the previous one, starting with the seed (counters, sequences).
A colleague removes elements from a list inside list.stream().forEach(...). What can happen, and what should they write instead?
The behaviour is undefined: elements may be skipped, a ConcurrentModificationException or even a NullPointerException may be thrown. Use list.removeIf(predicate) to remove in place, or list.stream().filter(...).toList() to build a new list.
Previous: Java Streams Explained: From Loops to Stream Pipelines
Related reading
- Java Lambda Variable Scope, Processing Lambdas and Comparator Methods
- Java Lambda Expressions and Functional Interfaces
- Java Collectors.toMap: Collecting Streams into Maps
- Collecting Java Stream Results: toList, toArray, joining and Summary Statistics
- Java Optional Best Practices: Pitfalls, Creating Optionals, flatMap and stream()

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.