This question already has an answer here:
In Java 8, the Stream
class does not have any method to wrap a an Iterable
.
Instead, I am obtaining the Spliterator
from the Iterable
and then obtaining a Stream
from StreamSupport
like this:
boolean parallel = true;
StreamSupport.stream(spliterator(), parallel)
.filter(Row::isEmpty)
.collect(Collectors.toList())
.forEach(this::deleteRow);
Is there some other way of generating Stream
operations on an Iterable
that I am missing?
My similar question got marked as duplicate, but here is the helper methods I've used to avoid some of the boilerplate:
public static <T> Stream<T> stream(Iterable<T> in) {
return StreamSupport.stream(in.spliterator(), false);
}
public static <T> Stream<T> parallelStream(Iterable<T> in) {
return StreamSupport.stream(in.spliterator(), true);
}
What you describe is the way to get a stream from an Iterable. That's why they added the spliterator() method to Iterable. I've done the same conversion myself and have not seen another way.
[UPDATE] Maybe this other answer will shed some clarification on the "why."
I know this doesn't directly answer your question, but a decent number of Iterable sources such as collections now have a method to get the object as a stream as well.
I think that the friction that you will run into with this question is that Iterable is semantically serial whereas Spliterators are meant to be used for processing in parallel. It is probably a better idea to implement a Spliterator for the underlying data source that you are interested in if it is not already provided in the JDK because just using a wrapper around the Iterable will not allow you to gain the benefits that the Stream API provide (such as parallel processing).
来源:https://stackoverflow.com/questions/20310209/how-to-perform-stream-functions-on-an-iterable