Streams flatMap
Description
Streams map() operation creates a one-to-one mapping.
Streams flatMap() supports one-to-many mapping. It maps each element to a stream and then flaten the stream of streams to a stream.
Example
The following code maps a stream of three numbers: 1, 2, and 3 to produce a stream that contains the numbers and their next numbers. The output stream should be 1,2,2,3,3,4.
import java.util.stream.Stream;
/*from w w w. j a v a 2 s.c o m*/
public class Main {
public static void main(String[] args) {
Stream.of(1, 2, 3)
.flatMap(n -> Stream.of(n, n+1))
.forEach(System.out::println);
}
}
The code above generates the following result.
Example 2
The following code shows how to convert a stream of strings to a stream of characters.
import java.util.stream.Stream;
// w ww.j av a2s. co m
public class Main {
public static void main(String[] args) {
Stream.of("XML", "Java", "CSS")
.map(name -> name.chars())
.flatMap(intStream -> intStream.mapToObj(n -> (char)n))
.forEach(System.out::println);
}
}
The code maps the strings to IntStream returns from chars()
method of the String class.
The output of the map()
method is Stream<IntStream>
.
The flatMap()
method maps the
Stream<IntStream>
to Stream<Stream<Character>>
and finally, flattens it to produce a Stream<Character>.
The code above generates the following result.
Example 3
The following code flatMaps the stream of string values to a IntStreams, then maps IntStream to Stream of characters.
import java.util.stream.IntStream;
import java.util.stream.Stream;
// www . j a va2 s. c om
public class Main {
public static void main(String[] args) {
Stream.of("XML", "Java", "CSS")
.flatMap(name -> IntStream.range(0, name.length())
.mapToObj(name::charAt))
.forEach(System.out::println);
}
}
The code above generates the following result.