Skip to content
Tutorials Center
My learning

Topics

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.

Java
List<Integer> lengths = words.stream().map(String::length).toList();

Try it

Java Transforming elements

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.

Java mapToInt, mapToObj and boxed

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

Java
<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() or mapMulti().
  • Prefer mapToInt for numbers. map(Integer::intValue).reduce(0, Integer::sum) boxes every value; mapToInt(...).sum() does not and gives you average() and summaryStatistics().
  • Null results are allowed from map; later operations such as sorted() or Collectors.toMap may then throw NullPointerException.
  • 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 limit or findFirst.
  • Side effects: do not use map just to run code; the call may never happen. Use forEach for 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 Stream yields Stream<Stream<T>>; that is the cue to use flatMap.