Difference between map and flatMap in java 8
map() and flatMap()
map() -
It processes stream of values.
It’s mapper function produces single value for each input value.
It is provide One-To-One mapping b/w input and output
flatMap()
It processes stream of stream of values.
It’s mapper function produces multiple values for each input value.
It is provide One-To-Many mapping b/w input and output
public class Example {
public static void main(String[] args) {
List<String> city = Arrays.asList(“Delhi”, “mirzapur”, “bsb”);
List<String> citys = Arrays.asList(“Delhi1”, “mirzapur1”, “bsb1”);
List<List<String>> list = Arrays.asList(city, citys);List<String> upper = city.stream().map(String::toUpperCase).collect(Collectors.toList());
System.out.println(“MAP — — — -”);
upper.forEach(System.out::println);List<String> flatupper = list.stream().flatMap(lists -> lists.stream()).filter(s > s.startsWith(“m”))
.collect(Collectors.toList());
System.out.println(“FLAT MAP — — — — -”);
flatupper.forEach(System.out::println);}