Difference between map and flatMap
Category : Java
| Sub Category : Java 8 Features | By Prasad Bonam Last updated: 2023-07-24 16:02:21
Viewed : 115
The key difference between
flatMap lies in their behavior when applied to collections or streams of elements:
map is a higher-order function that applies a transformation function to each element in the collection or stream and returns a new collection or stream with the transformed elements.
- The number of elements in the resulting collection or stream remains the same as the original collection or stream.
- It maintains a one-to-one relationship between elements in the original collection and the resulting collection.
- The transformation function can be used to convert each element to a different type, but it doesnt produce multiple elements for each input element.
List<Integer> numbers = Arrays.asList(1, 2, 3, 4);
List<Integer> squares = numbers.stream()
.map(num -> num * num)
In this example, each number in the
numbers list is squared using the
map function, and the resulting stream contains the squares of the numbers.
flatMap is also a higher-order function that applies a transformation function to each element in the collection or stream, but the difference is that the transformation function returns a collection or stream of elements for each input element.
flatMap function then flattens all the collections or streams obtained from the transformation function into a single collection or stream, merging all the elements into one flat structure.
- The number of elements in the resulting collection or stream may be different from the original collection or stream since each input element can produce multiple elements in the output.
List<List<Integer>> listOfLists = Arrays.asList(
Arrays.asList(1, 2, 3),
Arrays.asList(4, 5, 6),
Arrays.asList(7, 8, 9)
List<Integer> flattenedList = listOfLists.stream()
In this example,
flatMap is used to transform each nested list into a stream of elements, and then all those streams are flattened into a single list containing all the elements from the nested lists.
In summary, the primary distinction between
flatMap is that
map returns a collection or stream with the same number of elements, while
flatMap returns a collection or stream that may have a different number of elements due to the flattening process. Additionally,
map transforms elements one-to-one, while
flatMap can transform elements to multiple elements and then flatten the result.