[java] Convert Iterable to Stream using Java 8 JDK

I have an interface which returns java.lang.Iterable<T>.

I would like to manipulate that result using the Java 8 Stream API.

However Iterable can't "stream".

Any idea how to use the Iterable as a Stream without converting it to List?

This question is related to java java-8 java-stream iterable

The answer is


I would like to suggest using JOOL library, it hides spliterator magic behind the Seq.seq(iterable) call and also provides a whole bunch of additional useful functionality.


Another way to do it, with Java 8 and without external libs:

Stream.concat(collectionA.stream(), collectionB.stream())
      .collect(Collectors.toList())

So as another answer mentioned Guava has support for this by using:

Streams.stream(iterable);

I want to highlight that the implementation does something slightly different than other answers suggested. If the Iterable is of type Collection they cast it.

public static <T> Stream<T> stream(Iterable<T> iterable) {
  return (iterable instanceof Collection)
    ? ((Collection<T>) iterable).stream()
    : StreamSupport.stream(iterable.spliterator(), false);
}

public static <T> Stream<T> stream(Iterator<T> iterator) {
  return StreamSupport.stream(
    Spliterators.spliteratorUnknownSize(iterator, 0),
    false
  );
}

If you can use Guava library, since version 21, you can use

Streams.stream(iterable)

If you happen to use Vavr(formerly known as Javaslang), this can be as easy as:

Iterable i = //...
Stream.ofAll(i);

A very simple work-around for this issue is to create a Streamable<T> interface extending Iterable<T> that holds a default <T> stream() method.

interface Streamable<T> extends Iterable<T> {
    default Stream<T> stream() {
        return StreamSupport.stream(spliterator(), false);
    }
}

Now any of your Iterable<T>s can be trivially made streamable just by declaring them implements Streamable<T> instead of Iterable<T>.


I've created this class:

public class Streams {
    /**
     * Converts Iterable to stream
     */
    public static <T> Stream<T>  streamOf(final Iterable<T> iterable) {
        return toStream(iterable, false);
    }

    /**
     * Converts Iterable to parallel stream
     */
    public static <T> Stream<T> parallelStreamOf(final Iterable<T> iterable) {
        return toStream(iterable, true);
    }

    private static <T> Stream<T> toStream(final Iterable<T> iterable, final boolean isParallel) {
        return StreamSupport.stream(iterable.spliterator(), isParallel);
    }
}

I think it's perfectly readable because you don't have to think about spliterators and booleans (isParallel).


You can easily create a Stream out of an Iterable or Iterator:

public static <T> Stream<T> stream(Iterable<T> iterable) {
    return StreamSupport.stream(
        Spliterators.spliteratorUnknownSize(
            iterable.iterator(),
            Spliterator.ORDERED
        ),
        false
    );
}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to java-8

Default interface methods are only supported starting with Android N Class has been compiled by a more recent version of the Java Environment Why is ZoneOffset.UTC != ZoneId.of("UTC")? Modify property value of the objects in list using Java 8 streams How to use if-else logic in Java 8 stream forEach Android Studio Error: Error:CreateProcess error=216, This version of %1 is not compatible with the version of Windows you're running Error:could not create the Java Virtual Machine Error:A fatal exception has occured.Program will exit What are functional interfaces used for in Java 8? java.time.format.DateTimeParseException: Text could not be parsed at index 21 Java 8 lambda get and remove element from list

Examples related to java-stream

Sorting a list with stream.sorted() in Java Modify property value of the objects in list using Java 8 streams How to use if-else logic in Java 8 stream forEach Java 8 lambda get and remove element from list Create list of object from another using Java 8 Streams Java 8 Stream API to find Unique Object matching a property value Reverse a comparator in Java 8 Ignore duplicates when producing map using streams Modifying Objects within stream in Java8 while iterating How can I get a List from some class properties with Java 8 Stream?

Examples related to iterable

Convert Iterable to Stream using Java 8 JDK Python - TypeError: 'int' object is not iterable Get size of an Iterable in Java Convert Java Array to Iterable What exactly are iterator, iterable, and iteration? What is the difference between iterator and iterable and how to use them? Easy way to convert Iterable to Collection How do I add the contents of an iterable to a set? In Python, how do I determine if an object is iterable? Java: Get first item from a collection