Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Stream.map: practical reference

Stream.map: practical reference: map is a stateless one-to-one intermediate operation that lazily applies a Function to each consumed element and produces a stream of results.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

Stream.map(...)

map is a stateless one-to-one intermediate operation that lazily applies a Function to each consumed element and produces a stream of results.

Use it to project an object into another representation, such as an entity into a DTO; choose mapToInt, mapToLong, or mapToDouble for primitive results.

The mapper must be stateless and non-interfering; optimization or short-circuiting may skip side effects, and parallel execution may invoke it in different threads.

The mapper may return null and that element remains in the stream, but later findFirst, min, or max can then throw NullPointerException.

The example exercises the documented element in a small deterministic program and compares exact standard output.

Examples

public class Main {
    public static void main(String[] args) throws Exception {
        var result = java.util.stream.Stream.of("a", "bb").map(String::length).toList();
        System.out.println(result);
    }
}

Result

[1, 2]

The example exercises the documented element in a small deterministic program and compares exact standard output.

Sources