Iterable to Stream in Java

In this post of Java 8, we will see how to convert a Java Iterable into a Stream. We will look in to some stream operation after converting Iterable into a Stream.

 

1. Converting Java Iterable into a Stream

The Iterable interface serve a different purpose and that is one of the reason Java API does not provide any stream() method in this interface. One of the reason to not include stream method is the Iterable interface is because of its abstract nature. This interface does not carry any direct information about the size or characteristics and it will be difficult to perform any optimization on the Iterable interface or even to provide any parallel execution support.

To create stream from the Iterable, we can pass it to the StreamSupport.stream() method and get a Stream. The Iterable has a spliterator() method, so we should just use that to get the spliterator which we can pass to the StreamSupport.stream() method.Let’s see this in action:

Iterable<String> iterable= Arrays.asList("Testing", "Iterable", "To", "Java8", "Stream","Conversion");
 Stream streamList=  StreamSupport.stream(iterable.spliterator(), false);

The second parameter of the StreamSupport.stream() method determine if the returned stream is a parallel stream. if false the returned stream is a sequential stream.Once we get the Stream from the Iterable interface, we can execute any stream operation on it. Let’s see some operation in action:

public class IteratorToStream {

    public static void main(String[] args) {
        Iterable iterable
                = Arrays.asList("Testing", "Iterable", "To", "Java8", "Stream","Conversion");
        
        //Converting to the upper case
        List upperCaseList= StreamSupport.stream(iterable.spliterator(), false)
                                                 .map(String::toUpperCase)
                                                 .collect(Collectors.toList()); 
    }
}

 

Summary

Stream API provides a powerful way to work through the collections. In this short post, we saw how to convert a Java Iterable into a Stream. Keep in mind that Iterable can be used multiple time while we can consume Java stream only once. As always, the source code for this post is available on the GitHub.

Java Development Journal

Hello!! Welcome to the Java Development Journal. We love to share our knowledge with our readers and love to build a thriving community.

follow me on:

Leave a Reply

avatar

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
Notify of