CKTIS / Java
Collectors.mapping: practical reference
Collectors.mapping: practical reference: Collectors.mapping applies a mapping function to each input and forwards the mapped values to a downstream collector.
Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntax
Collectors.mapping(...)Collectors.mapping applies a mapping function to each input and forwards the mapped values to a downstream collector.
It is chiefly useful as a downstream collector, such as extracting names within each groupingBy bucket.
The mapper runs once for every accumulated element and may return null only if the downstream collector accepts null. Side effects in the mapper make parallel reduction harder to reason about.
For empty input the downstream collector supplies its empty result. Exceptions from the mapper or downstream collector propagate.
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 lengths = java.util.stream.Stream.of("aa", "b")
.collect(java.util.stream.Collectors.mapping(String::length, java.util.stream.Collectors.toList()));
System.out.println(lengths);
}
}
Result
[2, 1]
The example exercises the documented element in a small deterministic program and compares exact standard output.