What is flatMap() ? Write code for flatMap.

 Interview Question


Q. What is flatMap() ? Write code for flatMap.

Ans:- 

flatMap()  :- flatMap()  transform each element and flattern the resulting collection into a single combined collection.


Example of flatMap():-


package v1;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class FlatMapExample {

public static void main(String[] args) {
List<List<Integer>> list=new ArrayList<>();
list.add(Arrays.asList(1,2,3));
list.add(Arrays.asList(4,5,6));
list.add(Arrays.asList(7,8,9));
System.out.println(list);
List<Integer> flatList=list.stream().flatMap(i->i.stream().map(j->j*2)).collect(Collectors.toList());
System.out.println("FlatList:"+flatList);

}

}

************************************************************

Comments

Popular posts from this blog

What are POJO classes in spring? What is the use of POJO Class, and How to create POJO classes.

How to create React project using command prompt?