简体   繁体   中英

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?

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 .

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 (eg, in order to pass it on to some other API).

Just looking at the documentation , Stream#forEach is non-deterministic (eg, 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM