Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java

What is the Stream map() method in Java?

Tarun Telang

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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);
}
}
Demonstrating the usage of Stream map() method

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.

RELATED TAGS

java

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring