Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Stream — element-processing pipelines

Stream<T> processes object references through a lazy pipeline. Learn stream creation, result arrays, primitive mappings, and encounter-order guarantees.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

Stream.of(values).mapToInt(mapper)
Stream.of(values).mapToLong(mapper)
Stream.of(values).toArray()
Stream.of(values).toArray(String[]::new)
Stream.of(values).forEachOrdered(action)

java.util.stream.Stream<T> describes element processing, not a collection that stores data. A pipeline contains a source, intermediate operations, and a terminal operation. Intermediate operations are lazy: a terminal operation initiates processing.

Stream.of(T) creates a single-element stream; Stream.of(T... values) creates a sequential, ordered stream of the supplied values. Do not reuse a consumed stream; create a new one for another computation. Mapping functions should neither modify the source nor depend on mutable state.

Stream.toArray() terminates the pipeline, returning Object[]. The overload Stream.toArray(String[]::new) creates String[]; an incompatible element type causes ArrayStoreException. Stream.mapToInt and Stream.mapToLong are intermediate operations returning IntStream and LongStream, respectively. Their toArray() methods return int[] and long[], respectively, not wrapper-object arrays.

Stream.forEachOrdered terminates the pipeline, performing actions in encounter order when defined, including during parallel processing. It neither sorts the data nor guarantees a single thread for the actions. By contrast, parallel forEach does not guarantee ordering.

Documentation scope: Java SE 21; repository runtime, production runtime not attested.

Examples

import java.util.Arrays;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args) {
        String[] words = Stream.of("sun", "moon").toArray(String[]::new);
        int[] lengths = Stream.of(words).mapToInt(String::length).toArray();
        long[] sizes = Stream.of(words).mapToLong(s -> (long) s.length()).toArray();

        System.out.println(Arrays.toString(words));
        System.out.println(Arrays.toString(lengths));
        System.out.println(Arrays.toString(sizes));
        Stream.of(words).parallel().forEachOrdered(System.out::println);
    }
}

Result

[sun, moon]
[3, 4]
[3, 4]
sun
moon

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources