Stream map and flatMap

java.util.stream.Stream<T>
    <R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper);

Takes each element from the stream and apply function to create the stream of that element. All the new streams are flattened to one stream.

    List<List<String>> lists = asList(asList("a", "b"), asList("A", "B"), asList("1", "2", "3"));
    Stream<List<String>> stream = lists.stream();
    Stream<String> flatMappedStream = stream.flatMap(list -> {
        System.out.println("in flatMap: " + list);
        return list.stream();
    });

Up to this point nothing is printed since streams are “lazy”. Now Now let’s call the terminal operation like ‘forEach’:

    flatMappedStream
        .forEach(System.out::println);

Produces a stream of Strings:
Output:

in flatMap: [a, b]
a
b
in flatMap: [A, B]
A
B
in flatMap: [1, 2, 3]
1
2
3

java.util.stream.Stream<T>
    <R> Stream<R> map(Function<? super T, ? extends R> mapper);

Note that mapping function in flatMap(…) returns

? extends Stream<? extends R> 

where as mapping function in map(…) returns

? extends R

Takes each element from stream and apply the function to produce a result on it and replace each element with a result (not a stream). The output is a stream of results.

    List<List<String>> lists = asList(asList("a", "b"), asList("A", "B"), asList("1", "2", "3"));
    Stream<List<String>> stream = lists.stream();
    Stream<List<String>> mappedStream = stream.map(list -> {
        System.out.println("in map: " + list);
        return list;
    });

    mappedStream
        .forEach(System.out::println);

Produces a stream of Integers (representing each list size):
Output:

in map: [a, b]
2
in map: [A, B]
2
in map: [1, 2, 3]
3

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s