Can anyone explain this, I am trying cross Join implementation through flatmap?

Viewed 37
List<Integer> s1 = Stream.of(1, 2);
Supplier<Stream<String>> s2 = ()->Stream.of("A", "B");

s1.flatMap(v1 -> s2.get()
                   .map(v2 ->tuple(v1,v2))).forEach(System.out::println);

Flatmap argument need clarification.

1 Answers

First, there's a typo in the first line where Stream.of is assigned to List<Integer>

Regarding the explanation of flatMap argument:

  • Each integer from the s1 stream is mapped into Stream<tuple> containing several items: for each integer a string is picked from Stream<String>

  • Thus, these multiple Stream<tuple> should be flattened into a single Stream<tuple> which is consumed then in forEach terminal operation

List<Integer> s1 = Stream.of(1, 2);
Supplier<Stream<String>> s2 = () -> Stream.of("A", "B");

s1  // Stream<Integer>
.flatMap(v1 -> s2.get() // Stream<String> returned by the Supplier
                 .map(v2 -> tuple(v1,v2)) // Stream<tuple>
) // Stream<tuple>
.forEach(System.out::println);

For illustration, let's assume that a mere map is used instead of the flatMap (also using List instead of tuple):

s1  // Stream<Integer>
    .map(v1 -> s2.get() // Stream<String> returned by the Supplier
        .map(v2 -> Arrays.asList(v1, v2)) // Stream<List>
    ) // Stream<Stream<List>>
    .peek(System.out::println)
    .flatMap(s -> s) Stream<List>
    .forEach(System.out::println);

Output:

java.util.stream.ReferencePipeline$3@3dd4520b // printed by peek
[1, A]
[1, B]
java.util.stream.ReferencePipeline$3@5ae63ade // printed by peek
[2, A]
[2, B]
Related