import java.util.Arrays;
import java.util.stream.Stream;
public class FlatMapDemo
{
public static void main(String[] args)
{
String[][] strArray = new String[][] { { "a", "b" }, { "c", "d" }, { "e", "f" } };
// Stream<String[]>
Stream<String[]> strArrayStream = Arrays.stream(strArray);
//Convert Stream<String[]> to Stream<String>
Stream<String> strStream = strArrayStream.flatMap((x -> Arrays.stream(x)));
// filter a stream of string
Stream<String> filterdStream = strStream
.filter(x -> "c".equals(x.toString()));
filterdStream.forEach(System.out::println); //Output is c
}
}
Outputc
NonFlatMapDemo.javaimport java.util.Arrays;
import java.util.stream.Stream;
/**
*
* This example will print an empty result, because filter() has
* no idea how to filter a stream of String[].
*
*/
public class NonFlatMapDemo
{
public static void main(String[] args)
{
String[][] strArray = new String[][] { { "a", "b" }, { "c", "d" },{ "e", "f" } };
// Stream<String[]>
Stream<String[]> strArrayStream = Arrays.stream(strArray);
// filter a stream of string[], and return a string[]?
Stream<String[]> filterdStream = strArrayStream
.filter(x -> "c".equals(x.toString()));
filterdStream.forEach(System.out::println); //Output is empty...
}
}
Output//Output is empty...
Click the below link to download the code:https://sites.google.com/site/ramj2eev1/home/javabasics/StreamDemo_flatmap_App.zip?attredirects=0&d=1Github Link:https://github.com/ramram43210/Java/tree/master/BasicJava/StreamDemo_flatMapBitbucket Link:https://bitbucket.org/ramram43210/java/src/53e39342c1c41555c6e548783b3cf96ab7bd9ee6/BasicJava/StreamDemo_flatMap/?at=masterSee also: All JavaEE Viedos PlaylistAll JavaEE ViedosAll JAVA EE LinksServlets TutorialAll Design Patterns LinksJDBC TutorialJava Collection Framework TutorialJAVA TutorialKids Tutorial