Seshadri R
Seshadri R

Reputation: 1212

Why should I use collect(Collectors.toList()), when I can do without it?

I have seen the following code in many Java 8 reference materials and examples:

List <Integer> l = Arrays.asList(7, 3, 9, 8, 6, 5, -1, -100);  

l.stream().filter(y -> y <l.get(0)).collect(Collectors.toList()).
      forEach(System.out::println);

However, I am able to get the same result using:

l.stream().filter(y -> y <l.get(0)).forEach(System.out::println);

So, what is the sanctity of using collect(Collectors.toList()) that's used almost ubiquitously?

Upvotes: 2

Views: 3361

Answers (4)

Ravik
Ravik

Reputation: 734

Stream.collect(...) & Stream.forEach(...) are the operations to consume the result of the given stream's instance and they do not have any return type. So in your case you do not need both. Use collect(..) method when you need to get the result of stream output in a variable say list and use it later in the application.

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074305

Just looking at the documentation, Stream#forEach is non-deterministic (e.g., you can't know what order the elements will be visited in parallel streams in the general case). So I'd think you'd want to use collect(Collectors.asList()) when you need determinism in terms of the order you visit the elements (or, of course, any other time you want a list) and, of course, not when you don't.

In your specific example, you know the stream isn't parallel, because Collection#stream returns a sequential stream.

Upvotes: 3

Mureinik
Mureinik

Reputation: 311326

In this case, collecting the stream to a list is indeed pointless. Collecting should be used to create a list (or set, or map, or whatever) when you actually need a list object explicitly (e.g., in order to pass it on to some other API).

Upvotes: 3

Eran
Eran

Reputation: 393831

If all you care about is printing the elements that pass the filter, you don't need collect(Collectors.toList()).

Using ...collect(Collectors.toList()).forEach(System.out::println) is a waste, since it creates a List instance to which you don't keep a reference, and therefore can never access.

Use collect(Collectors.toList()) when you want to create a List of the elements of your Stream. You'd normally keep a reference to that List.

Upvotes: 9

Related Questions