In Java 8, the map() and flatMap() methods are used to manipulate elements of a stream.
The map() method applies a given function to each element of a stream and returns a new stream containing the results. The returned stream is of the same size as the original stream. Here’s an example:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> squaredNumbers = numbers.stream()
.map(num -> num * num)
.collect(Collectors.toList());
In this example, the map() method is used to square each element of the numbers list. The result is a new list called squaredNumbers that contains the squared values.
On the other hand, the flatMap() method is used to flatten a stream of streams into a single stream. It takes a function that returns a stream as an argument and applies it to each element of the original stream. The resulting stream is then flattened into a single stream. Here’s an example:
List<List<Integer>> nestedNumbers = Arrays.asList(
Arrays.asList(1, 2),
Arrays.asList(3, 4),
Arrays.asList(5, 6));
List<Integer> flattenedNumbers = nestedNumbers.stream()
.flatMap(numbers -> numbers.stream())
.collect(Collectors.toList());
In this example, the flatMap() method is used to flatten the nestedNumbers list into a single list called flattenedNumbers. The function passed to flatMap() returns a stream for each nested list, and flatMap() combines those streams into a single stream.
In summary, the map() method is used to transform each element of a stream, while the flatMap() method is used to transform each element of a stream into a new stream, and then combine all those streams into a single stream.
