Now there is a frequent scenario to convert Iterable to Stream as we are dealing with JPA repositories. Most of the JPA findByXXX methods return Iterable type.

Convert Iterable to Stream Java 8:

Stream API provides a lot of flexibility to access the Java collections, for example, filter based on specific conditions, grouping of items, getting min or max items and what not?

So being a fan of the Stream API, I would like to convert an Iterable into a Stream to make use of the stream operations. Let’s see how it can be achieved.

Iterable to Stream:

StreamSupport class having low-level utility methods for creating and manipulating the streams.

StreamSupport.stream(Spliterator<T> spliterator,boolean parallel) method provides the stream object, the second parameter represents the type of a stream which we need to get. If we need a parallel stream we have to pass true as a parameter otherwise false.

IterableToStream.java
import java.util.Arrays;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

public class IterableToStream {
    public static void main(String[] args) {
        Iterable<String> iterable
                = Arrays.asList("Apple", "Grapes", "Banana", "Mango");
        Stream<String> stream = StreamSupport.stream(iterable.spliterator(), false);
        // Applying stream operations (filtering). 
        stream.filter(fruits->fruits.startsWith("A")).forEach(System.out::print);
    }
}

Output:

Apple

References:

Happy Learning 🙂

About the Author:

Avatar
Founder of onlinetutorialspoint.com Love Java, Python, Shell and opensource frameworks. Follow him on twitter and facebook for latest updates.

Leave A Comment