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?
If you only want to iterate over the elements Stream, there is no need to collect it in Collection, just use forEach:
Stream
Collection
forEach
collection.stream() .filter(...) .forEach (item -> { // do something with item } );
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 .
Iterable - , ?
- Stream for-each, :
for-each
for (Item item : (Iterable<Item>) coll.stream().filter(...)::iterator) { }
Iterable<Item> iter = coll.stream().filter(...)::iterator; for (Item item : iter) { }
, Iterable , .
Iterable
, . forEach, , , "" . java.util.stream iterator "escape-hatch".
java.util.stream
iterator