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