Java Reference
In-Depth Information
1
4
9
16
25
The following snippet of code maps the elements of a stream of people to their names and prints the mapped
stream. Note that the map() method used in the code is the map() method of the Stream interface.
Person.persons()
.stream()
.map(Person::getName)
.forEach(System.out::println);
Ken
Jeff
Donna
Chris
Laynie
Li
Flattening Streams
In the previous section, you saw the map operation that facilitates a one-to-one mapping. Each element of the input
stream is mapped to an element in the output stream. The Streams API also supports one-to-many mapping through
the flatMap operation that works as follows:
It takes an input stream and produces an output stream using a mapping function.
The mapping function takes an element from the input stream and maps the element to a
stream. The type of input element and the elements in the mapped stream may be different.
This step produces a stream of streams. Suppose the input stream is a Stream<T> and the
mapped stream is Stream<Stream<R>> where T and R may be the same or different.
Finally, it flattens the output stream (that is, a stream of streams) to produce a stream. That is, the
Stream<Stream<R>> is flattened to Stream<R> .
It takes some time to understand the flat map operation. Suppose that you have a stream of three numbers: 1, 2,
and 3. You want to produce a stream that contains the numbers and the square of the numbers. You want the output
stream to contain 1, 1, 2, 4, 3, and 9. The following is the first, incorrect attempt to achieve this:
Stream.of(1, 2, 3)
.map(n -> Stream.of(n, n * n))
.forEach(System.out::println);
java.util.stream.ReferencePipeline$Head@372f7a8d
java.util.stream.ReferencePipeline$Head@2f92e0f4
java.util.stream.ReferencePipeline$Head@28a418fc
 
Search WWH ::




Custom Search