What is the Stream map() method in Java?

Overview

The Stream map() method is used to transform elements of a stream by applying a mapping function to each element. The mapped stream is then returned as a new stream.

This method accepts a Function mapper object as an argument. This function describes how each element in the original stream is transformed into an element in the new stream.

Visualizing the Stream map() function

Syntax

Stream map(Function mapper)
Syntax of Stream map() method

Parameters

  • mapper: This is a non-interfering, stateless function to apply to each element.

Return value

It returns the new stream consisting of the results of applying the given function to the elements of this stream.

Example

import java.util.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
Integer[] nums = {1, 2, 3, 4};
Stream<Integer> map = Arrays.stream(nums).map(n -> n * 2);
map.forEach(System.out::println);
}
}

Explanation

  • Line 7: We use the Arrays.stream() method to convert the integer array nums into a stream. This stream is mapped using the map() method. We pass a lambda function that multiplies each integer value by 2.
  • Line 9: We use the forEach() method to print out each element of the stream.

Free Resources