In Java 8, what's the difference between Stream.map
and Stream.flatMap
methods?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Stream operations
flatMap
andmap
accept a function as input.flatMap
expects the function to return a new stream for each element of the stream and returns a stream which combines all the elements of the streams returned by the function for each element. In other words, withflatMap
, for each element from the source, multiple elements will be created by the function. http://www.zoftino.com/java-stream-examples#flatmap-operationmap
expects the function to return a transformed value and returns a new stream containing the transformed elements. In other words, withmap
, for each element from the source, one transformed element will be created by the function. http://www.zoftino.com/java-stream-examples#map-operationAlso good analogy can be with C# if you familiar with. Basically C#
Select
similar to javamap
and C#SelectMany
javaflatMap
. Same applies to Kotlin for collections.Suppose we have:
flatMap
Let's take a
Function
that accepts one argument and produces aStream
of values:And apply this function to each list:
That's exactly what the
Stream.flatMap
can do:map
Let's take a
Function
that accepts one argument and produces one value:And apply this function to each list:
That's exactly what the
Stream.map
can do:One line answer:
flatMap
helps to flatten aCollection<Collection<T>>
into aCollection<T>
. In the same way, it will also flatten anOptional<Optional<T>>
intoOptional<T>
.As you can see, with
map()
only:Stream<List<Item>>
List<List<Item>>
and with
flatMap()
:Stream<Item>
List<Item>
This is the test result from the code used right below:
Code used:
I am not very sure I am supposed to answer this, but every time I face someone that does not understand this, I use the same example.
Imagine you have an apple. A
map
is transforming that apple toapple-juice
for example or a one-to-one mapping.Take that same apple and get only the seeds out of it, that is what
flatMap
does, or a one to many, one apple as input, many seeds as output.for a Map we have a list of elements and a (function,action) f so :
and for the flat map we have a list of elements list and we have a (function,action) f and we want the result to be flattened :