What is the fastest way to iterate over a thread in Java 8?

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

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

Which is faster? List or set? Is there a way to collect only Iterable or any other type that I can continue to?

+4
source share
3 answers

If you only want to iterate over the elements Stream, there is no need to collect it in Collection, just use forEach:

collection.stream()
          .filter(...)
          .forEach (item -> {
                            // do something with item
                            }
                   );
+9
source

If you do not need the order of the elements, use parallelStream:

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

This way you iterate over the collection using more threads.

, parallelStream , @Brian Goetz .

+3

Iterable - , ?

- Stream for-each, :

for (Item item : (Iterable<Item>)
        coll.stream().filter(...)::iterator) {
}

Iterable<Item> iter = coll.stream().filter(...)::iterator;
for (Item item : iter) {
}

, Iterable , .

, . forEach, , , "" . java.util.stream iterator "escape-hatch".

+2

All Articles