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

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

Leave a Reply

Your email address will not be published. Required fields are marked *

*