Alexey Galanov
Alexey Galanov

Reputation: 441

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?

Upvotes: 7

Views: 1512

Answers (1)

Paul Boddington
Paul Boddington

Reputation: 37645

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)

Upvotes: 9

Related Questions