1

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.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
kesari.j
  • 11
  • 1
  • 3
  • Did you go through the javadoc? – Naman Sep 08 '19 at 05:41
  • [Difference Between map() and flatMap() in Java](https://www.techiedelight.com/difference-map-flatmap-java/) – Ole V.V. Sep 08 '19 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](https://stackoverflow.com/posts/57839338/edit) link). – Ole V.V. Sep 08 '19 at 10:55

2 Answers2

0

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

Ani Aggarwal
  • 361
  • 4
  • 16
0

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()));
GnanaJeyam
  • 2,780
  • 16
  • 27