Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 4536

Iterable to Stream in Java

$
0
0

1. Overview

In this short tutorial, let’s convert a Java Iterable object into a Stream and perform some standard operations on it.

2. Converting Iterable to Stream

The Iterable interface is designed keeping generality in mind and does not provide any stream() method on its own.

Simply put, you can pass it to StreamSupport.stream() method and get a Stream from the given Iterable instance.

Let’s consider our Iterable instance:

Iterable<String> iterable 
  = Arrays.asList("Testing", "Iterable", "conversion", "to", "Stream");

And here’s how we can convert this Iterable instance into a Stream:

StreamSupport.stream(iterable.spliterator(), false);

Note that the second param in StreamSupport.stream() determines if the resulting Stream should be parallel or sequential. You should set it true, for a parallel Stream.

Now let’s test our implementation:

@Test
public void givenIterable_whenConvertedToStream_thenNotNull() {
    Iterable<String> iterable 
      = Arrays.asList("Testing", "Iterable", "conversion", "to", "Stream");

    Assert.assertNotNull(StreamSupport.stream(iterable.spliterator(), false));
}

Also, a quick side-note – streams are not reusable, while Iterable is; it also provides a spliterator() method, which returns a java.lang.Spliterator instance over the elements described by the given Iterable.

3. Performing Stream Operation

Let’s perform a simple stream operation:

@Test
public void whenConvertedToList_thenCorrect() {
    Iterable<String> iterable 
      = Arrays.asList("Testing", "Iterable", "conversion", "to", "Stream");

    List<String> result = StreamSupport.stream(iterable.spliterator(), false)
      .map(String::toUpperCase)
      .collect(Collectors.toList());

    assertThat(
      result, contains("TESTING", "ITERABLE", "CONVERSION", "TO", "STREAM"));
}

4. Conclusion

This simple tutorial shows how you can convert an Iterable instance into a Stream instance and perform standard operations on it, just like you would have done for any other Collection instance.

The implementation of all the code snippets can be found in the Github project.


Viewing all articles
Browse latest Browse all 4536

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>