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.
Stream map(Function mapper)
mapper
: This is a non-interfering, stateless function to apply to each element.It returns the new stream consisting of the results of applying the given function to the elements of this stream.
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);}}
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
.forEach()
method to print out each element of the stream.