"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > What\'s the Key Difference Between Stream.map() and Stream.flatMap() in Java 8?

What\'s the Key Difference Between Stream.map() and Stream.flatMap() in Java 8?

Published on 2024-11-15
Browse:936

What\'s the Key Difference Between Stream.map() and Stream.flatMap() in Java 8?

Stream.map() vs. Stream.flatMap() in Java 8

Stream.map() and Stream.flatMap() are two commonly used methods in Java 8 that perform similar transformations on a stream of values. However, they have a fundamental difference in how they process and return values.

Stream.map()

  • Accepts a Function super T, ? extends R> as an argument, where T is the input type and R is the output type.
  • Applies the given function to each element in the input stream.
  • Produces a new stream containing the transformed values, each corresponding to an input value.
  • For instance, given a stream of integers, map can be used to transform each integer into its square.

Stream.flatMap()

  • Accepts a Function super T, ? extends Stream extends R>> as an argument, which returns a stream for each input value.
  • Invokes the function on each element in the input stream.
  • The resulting streams are concatenated into a single stream, creating a "flattened" output.
  • For example, given a stream of strings, flatMap can be used to extract all individual characters into a single stream of characters.

Key Difference

The primary difference between map() and flatMap() lies in how they handle the results of the transformation function:

  • map() produces one transformed value for each input value.
  • flatMap() produces zero or more transformed values for each input value.

This distinction affects the shape and content of the resulting stream. flatMap() allows for the creation of nested streams, while map() maintains the same dimensionality of the original stream.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3