What are differences between map() and flatMap() in Java?

In Java, both the map and flatMap can be used with Stream. In both cases, it returns Stream.

In case of map

The map operation produces one output value for each input value.

Stream.map only applies to the stream without flattening the stream.

In case of faltMap

The flatMap operation produces arbitrary number values for each input value.

Stream.flatMap is the combination of a map and a flat operation on the stream.

Example

Consider the following data structure.

 
[[1, 2, 3], [5, 10, 15]]

The above data structure has two levels. Flattening the above data structure means to make it in one level like below:

 
[1, 2, 3, 5, 10, 15]