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.flatMap
, as it can be guessed by its name, is the combination of amap
and aflat
operation. That means that you first apply a function to your elements, and then flatten it.Stream.map
only applies a function to the stream without flattening the stream.To understand what flattening a stream consists in, consider a structure like
[ [1,2,3],[4,5,6],[7,8,9] ]
which has "two levels". Flattening this means transforming it in a "one level" structure :[ 1,2,3,4,5,6,7,8,9 ]
.Oracle's article on Optional highlights this difference between map and flatmap:
http://www.oracle.com/technetwork/articles/java/java8-optional-2175753.html
Both
map
andflatMap
can be applied to aStream<T>
and they both return aStream<R>
. The difference is that themap
operation produces one output value for each input value, whereas theflatMap
operation produces an arbitrary number (zero or more) values for each input value.This is reflected in the arguments to each operation.
The
map
operation takes aFunction
, which is called for each value in the input stream and produces one result value, which is sent to the output stream.The
flatMap
operation takes a function that conceptually wants to consume one value and produce an arbitrary number of values. However, in Java, it's cumbersome for a method to return an arbitrary number of values, since methods can return only zero or one value. One could imagine an API where the mapper function forflatMap
takes a value and returns an array or aList
of values, which are then sent to the output. Given that this is the streams library, a particularly apt way to represent an arbitrary number of return values is for the mapper function itself to return a stream! The values from the stream returned by the mapper are drained from the stream and are passed to the output stream. The "clumps" of values returned by each call to the mapper function are not distinguished at all in the output stream, thus the output is said to have been "flattened."Typical use is for the mapper function of
flatMap
to returnStream.empty()
if it wants to send zero values, or something likeStream.of(a, b, c)
if it wants to return several values. But of course any stream can be returned.flatMap()
also takes advantage of partial lazy evaluation of streams. It will read the fist stream and only when required, will go to the next stream. The behaviour is explained in detail here: Is flatMap guaranteed to be lazy?Map:- This method takes one Function as an argument and returns a new stream consisting of the results generated by applying the passed function to all the elements of the stream.
Let's imagine, I have a list of integer values ( 1,2,3,4,5 ) and one function interface whose logic is square of the passed integer. ( e -> e * e ).
output:-
As you can see, an output is a new stream whose values are square of values of the input stream.
http://codedestine.com/java-8-stream-map-method/
FlatMap :- This method takes one Function as an argument, this function accepts one parameter T as an input argument and returns one stream of parameter R as a return value. When this function is applied to each element of this stream, it produces a stream of new values. All the elements of these new streams generated by each element are then copied to a new stream, which will be a return value of this method.
Let's image, I have a list of student objects, where each student can opt for multiple subjects.
output:-
As you can see, an output is a new stream whose values are a collection of all the elements of the streams return by each element of the input stream.
[ S1 , S2 , S3 ] -> [ {"history","math","geography"}, {"economics","biology"}, {"science","math"} ] -> take unique subjects -> [economics, biology, geography, science, history, math]
http://codedestine.com/java-8-stream-flatmap-method/
map() in Java 8
a stream consisting of the results of applying the given function to the elements of this stream. Map takes an input which describes how the value needs to be transformed into. Suppose we want to get the age of the Student whose name is Saurabh, till now we have only retrieved the complete object from the stream but how do we do this ? We can use map() to transform the Student Stream into the age stream as below.
Now lets try to get all the names of the students with the help of collect()
map() vs flatMap()
Suppose we want to get all the courses available in students list then we can write the code as below:
**Here we will get a compilation error as below
Type mismatch: cannot convert from Set to Set To resolve this issue we use flatMap()**
flatMap() in Java 8
It returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element. flatMap will transform the stream of stream into simple stream. In below example we are using the flatMap to convert the Array of Stream into the String stream.
For more information you can refer to below links :
https://onlyfullstack.blogspot.com/2018/12/map-vs-flatmap-in-java-8.html
http://onlyfullstack.blogspot.com/p/java-8-features.html