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);
The output of this code would be:
2 4 6 8 10
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);
The output of this code would be:
h e l l o w o r l d j a v a
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!