Home > Java > javaTutorial > What is the difference between `map()` and `flatMap()` methods for stream processing in Java 8?

What is the difference between `map()` and `flatMap()` methods for stream processing in Java 8?

Barbara Streisand
Release: 2024-11-17 05:02:03
Original
485 people have browsed it

What is the difference between `map()` and `flatMap()` methods for stream processing in Java 8?

Stream Processing with map() and flatMap() Methods

In Java 8, the Stream interface provides two methods for processing streams of data: map() and flatMap(). Both methods take a function as an argument and produce a new stream, but they differ in the way they handle the results of applying the function to each element.

map() Method

The map() method applies the specified function to each element in the input stream, producing a new stream of the results. For example, the following code snippet uses map() to double the value of each integer in a list:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
numbers.stream()
        .map(i -> i * 2)
        .forEach(System.out::println);
Copy after login

The output of this code would be:

2
4
6
8
10
Copy after login

flatMap() Method

The flatMap() method also applies the specified function to each element in the input stream, but it does not produce a new stream of results. Instead, it combines the results of applying the function to each element into a single stream.

For example, the following code snippet uses flatMap() to concatenate the individual characters in a list of strings into a new stream:

List<String> words = Arrays.asList("hello", "world", "java");
words.stream()
        .flatMap(word -> Arrays.stream(word.split("")))
        .forEach(System.out::println);
Copy after login

The output of this code would be:

h
e
l
l
o
w
o
r
l
d
j
a
v
a
Copy after login

Key Difference

The key difference between map() and flatMap() is that map() produces a new stream of values, while flatMap() produces a flattened stream that combines the results of applying the function to each element.

The above is the detailed content of What is the difference between `map()` and `flatMap()` methods for stream processing in Java 8?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template