In java 8, when we should go for Stream.map and flat map methods ? I am bit confused about the use cases. Please give some scenarios to use these two methods.
-
Did you go through the javadoc?Naman– Naman2019-09-08 05:41:45 +00:00Commented Sep 8, 2019 at 5:41
-
Difference Between map() and flatMap() in JavaAnonymous– Anonymous2019-09-08 10:53:42 +00:00Commented Sep 8, 2019 at 10:53
-
It’s like your title and your text ask two different questions? Is the one in the text the question you intended to ask? Please edit your question and clarify and add precision (use the edit link).Anonymous– Anonymous2019-09-08 10:55:41 +00:00Commented Sep 8, 2019 at 10:55
2 Answers
Map is used when you want to transform a stream.
For example you have a shopping cart and for each item in your cart you would like to get the item detail or something else.
FlatMap combines the above map operation with a flat operation
Example could be something like you have bunch of orders and would like to know the total count of items sold for all orders. You could use a flatmap operation to get the number of items
Documentation helps btw
Comments
Map is used to transform the object from one stream to another.
For example:
class User {
private Long id;
public Long getId(){
return id;
}
}
Consider you have a list of users and your usecase is to get the user id's alone. Here comes advantage of Map.
List<User> users = new ArrayList<>();
List<Long> ids = users.stream().map(user ->
user.getId() ).collect(Collectors.toList());
FlatMap is also same as Map but it has another advantage of merging the multiple list into single list.
Example:
List<List<String>> stringlist = Arrays.asList( Arrays.asList("a"),
Arrays.asList("b") );
List<String> strings = stringlist.stream().flatMap(Collection::stream)
.collect(Collectors.toList()));