Java Reference ยท Streams and Functional
Java Stream.map() method
Reference for Java Stream.map(): transform each element with a Function, switch to primitive streams with mapToInt, and avoid common pitfalls.
map() is an intermediate operation that applies a Function to every element and produces a stream of the results. The number of elements stays the same; only their values (and possibly their type) change.
Besides map(), the stream interfaces offer mapToInt(), mapToLong() and mapToDouble(), which switch to a primitive stream and avoid boxing, and mapToObj() on primitive streams to go the other way.
List<Integer> lengths = words.stream().map(String::length).toList();
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
<R> Stream<R> map(Function<? super T, ? extends R> mapper) IntStream mapToInt(ToIntFunction<? super T> mapper) LongStream mapToLong(ToLongFunction<? super T> mapper) DoubleStream mapToDouble(ToDoubleFunction<? super T> mapper)
| Name | Description |
|---|---|
mapper |
A non-interfering, stateless function applied to each element. |
Returns: a stream of the mapped values, in the same order. Throws: NullPointerException if mapper is null.
Usage notes
- One in, one out. For zero or many results per element use
flatMap()ormapMulti(). - Prefer
mapToIntfor numbers.map(Integer::intValue).reduce(0, Integer::sum)boxes every value;mapToInt(...).sum()does not and gives youaverage()andsummaryStatistics(). - Null results are allowed from
map; later operations such assorted()orCollectors.toMapmay then throwNullPointerException. - Checked exceptions cannot be thrown from a lambda. Wrap the work in a helper that catches and rethrows an unchecked exception.
- Laziness: the function runs when the terminal operation pulls elements, and not at all for elements cut off by
limitorfindFirst. - Side effects: do not use
mapjust to run code; the call may never happen. UseforEachfor effects. - Type inference: when a lambda returns different types in different branches, give the target type explicitly with
Stream.<Number>map(...)or restructure. - Stream of streams: mapping to a
StreamyieldsStream<Stream<T>>; that is the cue to useflatMap.
Related
filter(),flatMap(),IntStream,Function,Optional.map()- Lessons: Streams, Method references