Java flatMap - what is the difference between stream.of () and collection.stream ()

I try to understand flatMap: it flatMap(x->stream.of(x) )does not align the flow, but flatMap(x->x.stream())works and gives the desired result. Can someone explain the difference between the two?

import java.util.*;
import java.util.stream.*;

class TestFlatMap{

    public static void main(String args[]){
        List<String> l1 = Arrays.asList("a","b");
        List<String> l2 = Arrays.asList("c","d");

        Stream.of(l1, l2).flatMap((x)->Stream.of(x)).forEach((x)->System.out.println(x));

        Stream.of(l1, l2).flatMap((x)->x.stream()).forEach((x)->System.out.println(x));
    }

}

Output:

[a, b]
[c, d]
a
b
c
d
+4
source share
2 answers

What you had in mind was the following:

Stream.of(l1, l2)
      // String[]::new isn't really needed in this simple example,
      // but would be in a more complex one...
      .flatMap((x)->Stream.of(x.toArray(String[]::new)))
      .forEach((x)->System.out.println(x));

Which will also give a tapered stream a, b, c, d, as you expected. Stream.of()comes in two versions:

List Stream.of() , , Stream<List<String>>, Stream<String>

+5

Stream.of(x) - x. flatMap Stream<List<String>> Stream<String>.

, x.stream(), x Collection<E>, a Stream<E>, Collection, Stream<String>, flatMap, Stream<String>, String List<String> Stream.

, Javadoc:

<T> Stream<T> java.util.stream.Stream.of(T t)
, .

.

Stream<E> stream()
.

+6

All Articles