Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8. Difference between collection.stream() and Stream.of(collection)

Could you please explain it to me? Why

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

and

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

are different?

like image 803
Alexey Galanov Avatar asked Nov 11 '15 18:11

Alexey Galanov


1 Answers

Stream does not have a Stream.of(Collection) method. It does have a method

static <T> Stream<T> of(T t)

If you pass a Collection to this method you'll get a Stream<Collection> containing one element (the Collection), not a stream of the collection's elements.

As an example, try this:

List<Integer> l1 = Arrays.asList(1, 2, 3);
List<Integer> l2 = Arrays.asList(4, 5, 6);
Stream.of(l1, l2).flatMap((x)->x.stream()).forEach((x)->System.out.println(x));
Stream.of(l1, l2).flatMap((x)->Stream.of(x)).forEach((x)->System.out.println(x));

The first version prints:

1
2
3
4
5
6

The second version prints:

[1, 2, 3]
[4, 5, 6]

Note that if arr is an Object[] you can do Stream.of(arr) to get a stream of the array's elements. This is because there is another version of of that uses varargs.

static <T> Stream<T> of(T... values)
like image 61
Paul Boddington Avatar answered Nov 12 '22 02:11

Paul Boddington