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 code backing this article is available on GitHub. Once you're
logged in as a Baeldung Pro Member, start learning and coding on the project.