What’s the difference between map() and flatMap() methods in Java 8?

By | March 23, 2023

In Java 8, map() and flatMap() are two commonly used methods in the Stream API. Both methods are used to transform a Stream of elements, but they have different behaviors.

map() method applies a given function to each element of the stream and returns a new stream with the results. The type of the new stream can be different from the original stream.

Here’s an example of map() method:

List<String> words = Arrays.asList(“Hello”, “World”);

// transform the words to uppercase

List<String> upperCaseWords = words.stream()

                                    .map(String::toUpperCase)

                                    .collect(Collectors.toList());

The output of this example would be a list containing “HELLO” and “WORLD”.

flatMap() method, on the other hand, applies a function that returns a stream to each element of the original stream, and then flattens the resulting streams into a single stream of elements. The type of the new stream must be the same as the original stream.

Here’s an example of flatMap() method:

List<List<Integer>> numbers = Arrays.asList(

                                Arrays.asList(1, 2, 3),

                                Arrays.asList(4, 5, 6),

                                Arrays.asList(7, 8, 9));

// flatten the list of lists to a single list of integers

List<Integer> flattenedNumbers = numbers.stream()

                                         .flatMap(Collection::stream)

                                         .collect(Collectors.toList());

The output of this example would be a list containing 1, 2, 3, 4, 5, 6

Leave a Reply

Your email address will not be published. Required fields are marked *