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.

3
  • Did you go through the javadoc? Commented Sep 8, 2019 at 5:41
  • Difference Between map() and flatMap() in Java Commented 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). Commented Sep 8, 2019 at 10:55

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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()));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.