Member-only story
How does flatMap differ from a map in Java Streams?
100 Days 100+ Interview Questions
100 Days — 100+ Interview Questions
Hey friend,
From today, we will learn 100+ Interview Questions in 100 Days with complete, detailed explanations from scratch, which will help us understand concepts better and help us crack interviews.
You can get the complete Interview Series here.
Question
How does flatMap() differ from map() in Java Streams?
In our past blog we have discussed what Stream API is in Java. I would recommend to go throught the above blog if you are not aware of stream API. In this blog we will discuss about what is flatMap() and map() and their differences.
map()
Let’s consider an array where we have list of names and we want to loop and print the size of each names.
List<String> names = Arrays.asList("Pavan", "Sai", "Medium");
for (int i = 0; i < names.size(); i++) {
System.out.println(names.get(i).length());
}
- Now if we want to use the Stream API, How we will do that?
- Map is used to perform some transformations meaning , let’s say we wanted to…