Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the fastest way to iterate on a stream in Java 8?

If I have a collection and I want to iterate over a filtered stream then I could do either of the following (and many more obtuse options):

for(item in collection.stream().filter(...).collect(Collectors.toList()))
for(item in collection.stream().filter(...).collect(Collectors.toSet()))

Which is faster? A list or a set? Is there some way to collect to simply an Iterable or some other type I can iterate on?

like image 834
Pace Avatar asked Apr 28 '15 15:04

Pace


2 Answers

If you only want to iterate over the elements of the Stream, there's no need to collect it into a Collection, just use forEach :

collection.stream()
          .filter(...)
          .forEach (item -> {
                            // do something with item
                            }
                   );
like image 191
Eran Avatar answered Oct 21 '22 04:10

Eran


If you don't care about elements order use parallelStream:

collection.parallelStream().filter(...).forEach(...)

This way you iterate through the collection using more threads.

To mesure which stream or parallelStream procesing is faster for a specific case review @Brian Goetz answer for the related problem

like image 21
Karol Król Avatar answered Oct 21 '22 05:10

Karol Król