einer der Sucher einer der Sucher - 2 years ago 116
Java Question

Java flatMap - whats the difference stream.of() and collection.stream()

I'm trying to understand

flatMap(x->stream.of(x) )
does not flat the stream and
works and gives the desired result.
Can someone explain the difference between 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]

Answer Source

The thing you had in mind was this:

Stream.of(l1, l2)
      // String[]::new isn't really needed in this simple example,
      // but would be in a more complex one...

Which would also yield a flattened stream of a, b, c, d as you expected. Stream.of() comes in two flavours:

Since, when passing a List to Stream.of(), the only applicable overload is the one taking a single value, you got a Stream<List<String>> rather than the expected Stream<String>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download