How to perform Stream functions on an Iterable?

The Coordinator picture The Coordinator · Dec 1, 2013 · Viewed 14.2k times · Source

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?

Answer

Scott B picture Scott B · Apr 4, 2014

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);
}