Home / JAVA Complete Reference by Examples / Streams / How to use flatMap stream method in Java 8 by Example
How to use flatMap stream method in Java 8 by Example
2468 views.
package com.learnbyexamples.streams;

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

/**
 * map and flatMap can be applied to a Stream<T> and they both return
 * a Stream<R>. The difference is that the map operation produces one
 * output value for each input value, whereas the flatMap operation
 * produces an arbitrary number (zero or more) values for each input value.
 *
 */
public class E008_FlatMapStream {
    public static void main(String[] args) {
        /*
         * Convert all names into List<String>
         */
        String[] familyNames = {"Raja,Vimala",
                                "Siva,Ammu",
                                "Ramkumar","Amudha"};
        
        //Converting all names into Stream<String>
        //flatMap consume one elements return Stream<Element>
        Stream<String> familyNamesStream = Arrays.stream(familyNames);
        
        //Spliting all names in the string and converting into List of single names.
        List<String> names = familyNamesStream.flatMap(name -> Arrays.stream(name.split(","))).collect(Collectors.toList());
        
        //Print names
        System.out.println(names);
    }
}
Output
[Raja, Vimala, Siva, Ammu, Ramkumar, Amudha]
Related Examples
   How to filter an List stream using Lambda expression in Java 8 by Example
   How to filter an Array stream using Lambda expression in Java 8 by Example
   How to filter an Map stream using Lambda expression in Java 8 by Example
   How to use Stream generate method using Lamdba expression in Java 8 Example
   How to read a file line by line using stream in Java 8 by Example
   How to split string into stream in Java 8 by Example
   How to transform stream elements using map in Java 8 by Example
   How to use flatMap stream method in Java 8 by Example
Copyright © 2016 Learn by Examples, All rights reserved