Friday, 8 July 2016

Textual description of firstImageUrl

Jav 8 FlatMap Explained Stream API

In this short example , i will explain where we can use flatMap function of java stream api .

Suppose you have a multi level list where many objects are stored , and you want to convert it to a single list of objects . We can use flatmap which will flatten the list easily .

FlatMap basically first applies the transformation , and then then flatten the result in a single collection .

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

/**
 * Created by abhishek.somani on 8/7/16.
 */
public class JavarootsFlatMapExample {

    public static void main(String[] args) {
        String[] arr = {"abhishekl","somani"};
        String[] arr2 = {"java","example","1.8","stream"};
        List<List<String>> list = new ArrayList<>();
        list.add(Arrays.asList(arr));
        list.add(Arrays.asList(arr2));
        final List<String> strings = list.stream().flatMap(l -> l.stream()).collect(Collectors.toList());
        System.out.println(strings);
    }

}
Post Comments And Suggestions !!!