Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Stream.map()

Transforms every element of a stream.

Available since: Java 8

Syntax

<R> Stream<R> map(Function<? super T, ? extends R> mapper)

Parameters

ParameterTypeDescription
mapperFunction<? super T, ? extends R>A function that turns an element into a new value.

Return value

Stream<R>A stream of the function results.

Examples

String lengths:

void main() {
    List<Integer> lengths = List.of("Java", "Go", "Kotlin").stream()
        .map(String::length)
        .toList();
    IO.println(lengths);
}

Output:

[4, 2, 6]

One field from each record:

record User(String name, String email) {}
 
void main() {
    var users = List.of(new User("Anna", "anna@mail.com"), new User("Oleg", "oleg@mail.com"));
    String emails = users.stream().map(User::email).collect(Collectors.joining("; "));
    IO.println(emails);
}

Output:

anna@mail.com; oleg@mail.com

Notes

The number of elements stays the same — each input gives one output. The type may change: a Stream<String> can become a Stream<Integer>. For numbers prefer mapToInt() to get sum() and average(). If the function returns a collection and you need a flat stream, use flatMap().

See also

  • Stream.filter() — Keeps only the stream elements that match a condition.
  • Stream.flatMap() — Turns each element into a stream and joins all streams into one.
  • Stream.mapToInt() — Turns a stream of objects into a stream of `int` numbers.
  • Function — A function that takes a value of type `T` and returns a value of type `R`.

Related recipes

In the tutorial

  • Stream operations — The main Stream API operations — filter, map, sorted, distinct, limit, skip, count, reduce, anyMatch, findFirst and numeric streams.

Thanks for reading!

Donate to the site — we work hard for you.