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?
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
}
);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With