What's the difference between map() and flatMap() methods in Java 8?
In Java 8, the map()
and flatMap()
methods are part of the Stream
API, and are used to transform the elements of a stream.
The map()
method applies a function to each element of a stream, and returns a new stream that contains the transformed elements. The function is applied to each element of the stream one at a time, and the transformed elements are collected into a new stream.
For example, given a stream of strings, you can use the map()
method to transform the strings into integers, like this:
List<String> strings = Arrays.asList("1", "2", "3", "4", "5");
Stream<Integer> integers = strings.stream().map(Integer::parseInt);
// integers is a stream of [1, 2, 3, 4, 5]
The flatMap()
method works similarly to the map()
method, but instead of returning a stream of transformed elements, it flattens the elements of the stream into a single stream.
For example, given a stream of lists, you can use the flatMap()
method to flatten the lists into a single stream of elements, like this:
List<List<String>> lists = Arrays.asList(
Arrays.asList("a", "b"),
Arrays.asList("c", "d"),
Arrays.asList("e", "f")
);
Stream<String> strings = lists.stream().flatMap(List::stream);
// strings is a stream of ["a", "b", "c", "d", "e", "f"]
In summary, the map()
method applies a function to each element of a stream and returns a new stream of transformed elements, while the flatMap()
method flattens the elements of a stream into a single stream.