Java 8 Stream Example: flatMap()

Below is the example of Java 8 Stream flatMap().

It returns a stream of object after applying a mapping function to each element and then flattens the result.

package the.basic.tech.info;

import java.util.Arrays;

public class StreamFlatMapExample {
	public static void main(String[] args) {
		Integer[][] data = { { 1, 2 }, { 3, 4 }, { 5, 6 } };
		Arrays.stream(data).flatMap(row -> Arrays.stream(row)).filter(num -> num % 2 == 0)
				.forEach(s -> System.out.print(s + " "));
	}
}

Output
2 4 6 
package the.basic.tech.info;

import java.util.Arrays;

public class StreamFlatMapExample {
	public static void main(String[] args) {
		Integer[][] data = { { 1, 3, 9, 11 }, { 2, 4 }, { 2, 5, 6, 17, 21, 30} };
		Arrays.stream(data).flatMap(row -> Arrays.stream(row)).filter(num -> num % 2 == 0)
				.forEach(s -> System.out.print(s + " "));
	}
}

Output
2 4 2 6 30