Collecting Java Stream Results: toList, toArray, joining and Summary Statistics
Get results out of a Java stream: iterator, forEach versus forEachOrdered, typed arrays with toArray(String[]::new), the differences between toList(), Collectors.toList() and toUnmodifiableList(), toSet, toCollection, joining and summarizingInt statistics.
kvi5hnuCode Sprout team member8 min readOn this page
When a pipeline is done, you usually want the results somewhere you can use them: a list, an array, a string, a set or some statistics. This article covers the terminal operations that hand you the elements (iterator, forEach, toList, toArray) and introduces collectors, the objects you pass to collect to gather elements into almost any shape. The next four articles build on collectors to produce maps, groups and custom results.
Visiting the elements
iterator() gives you an old-fashioned Iterator, which is useful when you must hand the results to an API that expects one, or when you want to pull elements one at a time under your own control:
Iterator<Integer> iter = Stream.iterate(0, n -> n + 1).limit(10).iterator();
while (iter.hasNext()) System.out.println(iter.next());
forEach(action) applies a function to every element:
stream.forEach(System.out::println);
On a parallel stream, forEach visits elements in whatever order the threads happen to produce them, possibly from several threads at once. If the order matters, use forEachOrdered, which respects the stream's encounter order. That may cost some or all of the benefit of parallelism, since threads have to wait for each other.
forEach is meant for side effects such as printing or sending. It's tempting to "collect" by adding to a list inside forEach, but don't. With a parallel stream, several threads would call add on an ArrayList at once and corrupt it. Collecting is what toList() and collect are for, and they're safe in parallel.
Collecting into a list
You've already used toList() (Java 16). It returns a list of the stream's elements in encounter order. There are actually three ways to get a list, and they differ in subtle ways:
| Expression | Modifiable? | Allows null elements? |
|---|---|---|
stream.toList() (Java 16) | no, throws UnsupportedOperationException | yes |
stream.collect(Collectors.toList()) | not guaranteed (today it's an ArrayList) | yes |
stream.collect(Collectors.toUnmodifiableList()) (Java 10) | no | no, throws NullPointerException |
In new code, toList() is the natural choice: short, efficient and unmodifiable. If you need to add to the result afterwards, ask for a specific type with collect(Collectors.toCollection(ArrayList::new)). Relying on Collectors.toList() being mutable works today, but the documentation makes no promise about the type, mutability, serializability or thread safety of the list.
Collecting into an array
toArray() returns an array of the elements. Because Java can't create a generic array T[] at runtime, the no-argument version returns an Object[], and casting it to String[] or Integer[] fails with a ClassCastException. The array object really is an Object[], even though its elements are Integers. To get an array of the right type, pass an array constructor reference:
String[] result = stream.toArray(String[]::new);
The argument is an IntFunction<A[]>: the stream calls it with the required size and fills the returned array. String[]::new is shorthand for n -> new String[n]. For primitive streams, intStream.toArray() returns an int[] directly.
Collectors and the collect method
For everything else, Stream has a general collect method that takes a Collector. A collector is an object that knows how to accumulate elements into some result container and produce a final result. You rarely implement one yourself (article 12 shows how). Instead you get them from static factory methods in the Collectors class:
Set<String> set = stream.collect(Collectors.toSet());
TreeSet<String> sorted = stream.collect(Collectors.toCollection(TreeSet::new));
toSet() gives you some Set with no promises about which kind, typically a HashSet. toUnmodifiableSet() (Java 10) gives an unmodifiable one. When you need a particular kind of collection, such as a TreeSet for sorted order, a LinkedHashSet for insertion order or an ArrayDeque, use toCollection with a constructor reference.
Note that joining, toSet and the others are static methods of Collectors that produce Collector objects. You don't call them on the stream. You pass their result to collect. Many programmers write import static java.util.stream.Collectors.*; so they can say stream.collect(toSet()).
Joining strings
Collectors.joining() concatenates a stream of strings (any CharSequence). Give it a delimiter, and optionally a prefix and suffix:
String result = stream.collect(Collectors.joining()); // "abc"
String result = stream.collect(Collectors.joining(", ")); // "a, b, c"
String result = stream.collect(Collectors.joining(", ", "[", "]")); // "[a, b, c]"
The prefix and suffix appear even for an empty stream, giving "[]". If the elements aren't strings, convert them first: stream.map(Object::toString).collect(Collectors.joining(", ")). String.join(", ", list) does the same job without a stream when you already have a collection of strings.
Summary statistics
To get the count, sum, average, minimum and maximum of a numeric property in one pass, use summarizingInt, summarizingLong or summarizingDouble. Each takes a function that maps an element to a number:
IntSummaryStatistics summary = words.collect(Collectors.summarizingInt(String::length));
double averageWordLength = summary.getAverage();
int maxWordLength = summary.getMax();
Watch the empty case. With no elements, getCount() and getSum() are 0 and getAverage() is 0.0, but getMax() returns Integer.MIN_VALUE and getMin() returns Integer.MAX_VALUE (Long.MIN_VALUE/Long.MAX_VALUE for LongSummaryStatistics; for DoubleSummaryStatistics they are Double.NEGATIVE_INFINITY and Double.POSITIVE_INFINITY, not Double.MIN_VALUE, which is the smallest positive double). Those are the neutral starting values, so check getCount() before trusting the minimum or maximum. Primitive streams offer the same statistics directly: intStream.summaryStatistics().
A complete example
The example removes the vowels from the words of a sentence and collects the results in various ways.
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";
static Stream<String> noVowels() {
return Stream.of(TEXT.split("\\PL+")).map(s -> s.replaceAll("[aeiouAEIOU]", ""));
}
public static void main(String[] args) {
// an old-fashioned iterator
Iterator<Integer> iter = Stream.iterate(0, n -> n + 1).limit(5).iterator();
var sb = new StringBuilder("iterator:");
while (iter.hasNext()) sb.append(' ').append(iter.next());
System.out.println(sb);
// forEach and forEachOrdered
System.out.print("forEach:");
noVowels().limit(5).forEach(s -> System.out.print(" " + s));
System.out.println();
System.out.print("parallel forEachOrdered:");
noVowels().parallel().limit(5).forEachOrdered(s -> System.out.print(" " + s));
System.out.println();
// arrays
Object[] numbers = Stream.iterate(0, n -> n + 1).limit(5).toArray();
System.out.println("toArray(): " + numbers.getClass().getSimpleName() + " " + Arrays.toString(numbers));
try {
Integer[] wrong = (Integer[]) numbers;
System.out.println(wrong.length);
} catch (ClassCastException e) {
System.out.println("casting it to Integer[]: ClassCastException");
}
Integer[] typed = Stream.iterate(0, n -> n + 1).limit(5).toArray(Integer[]::new);
System.out.println("toArray(Integer[]::new): " + typed.getClass().getSimpleName() + " " + Arrays.toString(typed));
// joining
System.out.println("joining(): " + noVowels().limit(5).collect(Collectors.joining()));
System.out.println("joining(\", \"): " + noVowels().limit(5).collect(Collectors.joining(", ")));
System.out.println("with prefix: " + noVowels().limit(5).collect(Collectors.joining(", ", "[", "]")));
System.out.println("non-strings: " + Stream.of(1, 2, 3).map(Object::toString).collect(Collectors.joining(" + ")));
// summary statistics
IntSummaryStatistics summary = Stream.of(TEXT.split("\\PL+")).collect(Collectors.summarizingInt(String::length));
System.out.println("summary: " + summary);
System.out.printf("average word length %.2f, longest %d%n", summary.getAverage(), summary.getMax());
IntSummaryStatistics none = Stream.<String>empty().collect(Collectors.summarizingInt(String::length));
System.out.println("empty: count " + none.getCount() + ", average " + none.getAverage()
+ ", max " + none.getMax() + " (Integer.MIN_VALUE)");
// lists: toList() vs Collectors.toList() vs toUnmodifiableList()
List<String> a = Stream.of("x", "y").toList();
List<String> b = Stream.of("x", "y").collect(Collectors.toList());
b.add("z");
System.out.println("Collectors.toList() is modifiable in practice: " + b);
try {
a.add("z");
} catch (UnsupportedOperationException e) {
System.out.println("toList() is unmodifiable: UnsupportedOperationException");
}
System.out.println("toList() allows null: " + Stream.of("x", null).toList());
try {
Stream.of("x", null).collect(Collectors.toUnmodifiableList());
} catch (NullPointerException e) {
System.out.println("toUnmodifiableList() rejects null: NullPointerException");
}
// sets and specific collections
Set<String> set = Stream.of("b", "a", "b", "c").collect(Collectors.toSet());
System.out.println("toSet size: " + set.size());
TreeSet<String> sorted = noVowels().collect(Collectors.toCollection(TreeSet::new));
System.out.println("toCollection(TreeSet::new): " + sorted);
ArrayDeque<Integer> deque = IntStream.rangeClosed(1, 4).boxed().collect(Collectors.toCollection(ArrayDeque::new));
System.out.println("toCollection(ArrayDeque::new), pop: " + deque.pop());
}
}
iterator: 0 1 2 3 4
forEach: lc ws bgnnng t gt
parallel forEachOrdered: lc ws bgnnng t gt
toArray(): Object[] [0, 1, 2, 3, 4]
casting it to Integer[]: ClassCastException
toArray(Integer[]::new): Integer[] [0, 1, 2, 3, 4]
joining(): lcwsbgnnngtgt
joining(", "): lc, ws, bgnnng, t, gt
with prefix: [lc, ws, bgnnng, t, gt]
non-strings: 1 + 2 + 3
summary: IntSummaryStatistics{count=15, sum=60, min=2, average=4.000000, max=9}
average word length 4.00, longest 9
empty: count 0, average 0.0, max -2147483648 (Integer.MIN_VALUE)
Collectors.toList() is modifiable in practice: [x, y, z]
toList() is unmodifiable: UnsupportedOperationException
toList() allows null: [x, null]
toUnmodifiableList() rejects null: NullPointerException
toSet size: 3
toCollection(TreeSet::new): [bgnnng, bnk, by, f, gt, hr, lc, n, sstr, sttng, t, th, trd, vry, ws]
toCollection(ArrayDeque::new), pop: 1
Common questions
Which list should I return from a public method?
toList(), which is unmodifiable, is the safe default. Callers cannot accidentally change your internal data, and the intent is clear. Return a mutable ArrayList (with toCollection(ArrayList::new)) only when callers are expected to modify the result.
Why does toList() accept null while List.of does not?
toList() must be able to collect any stream, including one with null elements, so it was specified to allow them. List.of, List.copyOf and Collectors.toUnmodifiableList() reject null with a NullPointerException.
How do I collect into an int[] instead of an Integer[]?
Map to a primitive stream first: stream.mapToInt(Integer::intValue).toArray(). toArray(Integer[]::new) gives an array of boxed values.
Can I convert a List to an array without a stream?
Yes: list.toArray(String[]::new) (Java 11) or list.toArray(new String[0]). Streams are only needed when a pipeline comes first.
How do I join numbers with a comma?
Convert them to strings first: numbers.stream().map(String::valueOf).collect(Collectors.joining(", ")). joining accepts only CharSequence elements.
Does forEachOrdered make a parallel stream sequential?
No. The preceding operations still run in parallel; only the final action is performed one element at a time in encounter order. If that action dominates the cost, the parallel stream gains little.
API reference
java.util.stream.Stream<T> and BaseStream
| Method | Description |
|---|---|
Iterator<T> iterator() | an iterator over the elements (terminal) |
void forEach(Consumer<? super T> action) | applies action to each element, in any order for parallel streams |
void forEachOrdered(Consumer<? super T> action) | applies action in encounter order |
List<T> toList() (Java 16) | an unmodifiable list of the elements; nulls allowed |
Object[] toArray(), <A> A[] toArray(IntFunction<A[]> generator) | an Object[], or an array created by generator, such as String[]::new |
<R, A> R collect(Collector<? super T, A, R> collector) | collects the elements with the given collector |
java.util.stream.Collectors
| Method | Description |
|---|---|
toList(), toUnmodifiableList() (Java 10) | collect into a list |
toSet(), toUnmodifiableSet() (Java 10) | collect into a set |
toCollection(Supplier<C> collectionFactory) | collect into the collection that the factory creates, such as TreeSet::new |
joining(), joining(CharSequence delimiter), joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix) | concatenate strings |
summarizingInt(ToIntFunction<? super T> mapper), summarizingLong(...), summarizingDouble(...) | an Int/Long/DoubleSummaryStatistics of the mapped values |
java.util.IntSummaryStatistics, LongSummaryStatistics, DoubleSummaryStatistics
| Method | Description |
|---|---|
long getCount() | the number of values |
getSum(), double getAverage() | the sum and average; 0 for no values |
getMax(), getMin() | the maximum and minimum; for no values MIN_VALUE/MAX_VALUE (int, long) or negative/positive infinity (double) |
Summary
iterator()andforEachvisit the results. UseforEachOrderedwhen order matters in a parallel stream, and never collect by mutating a list insideforEach.toList()returns an unmodifiable list that allowsnull.Collectors.toList()makes no guarantees.toUnmodifiableList()rejectsnull.toArray(String[]::new)gives a typed array. The plaintoArray()returns anObject[]that can't be cast to a more specific array type.collecttakes aCollectorfrom theCollectorsfactory methods:toSet,toCollection,joining,summarizingIntand many more.- Summary statistics compute count, sum, average, minimum and maximum in one pass. For an empty stream, minimum and maximum are the extreme sentinel values.
Practice Questions
Why does (String[]) stream.toArray() throw a ClassCastException even though all elements are strings?
toArray() creates an array whose runtime type is Object[], because the stream can't create a generic array of the element type. A cast checks the array's runtime type, not its contents, so it fails. Use stream.toArray(String[]::new).
Your code does var list = stream.toList(); list.add(x); and fails at runtime. What are two fixes?
toList() returns an unmodifiable list. Either collect into a mutable list explicitly with stream.collect(Collectors.toCollection(ArrayList::new)), or copy the result: new ArrayList<>(stream.toList()).
What does Stream.of("a", "b", "c").collect(Collectors.joining("-", "<", ">")) produce? What about an empty stream?
"<a-b-c>". For an empty stream, the result is "<>", because the prefix and suffix are always added.
A summarizingInt over an empty stream reports getMax() == -2147483648. Is that a bug?
No. That's Integer.MIN_VALUE, the neutral starting value for a maximum. With no elements, nothing ever replaces it. Check getCount() > 0 before using the minimum or maximum.
How do you collect the words of a stream into a set that keeps them sorted alphabetically?
words.collect(Collectors.toCollection(TreeSet::new)). A TreeSet keeps its elements in sorted order. Collectors.toSet() makes no promise about the kind of set or its order.
Previous: Java Optional Best Practices: Pitfalls, Creating Optionals, flatMap and stream()
Related reading
- Java Lambda Variable Scope, Processing Lambdas and Comparator Methods
- Java Lambda Expressions and Functional Interfaces
- Java Collectors.toMap: Collecting Streams into Maps
- Java Optional Best Practices: Pitfalls, Creating Optionals, flatMap and stream()
- Java Optional: Getting, Consuming and Transforming Optional Values

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.