
Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:
Once the early-adopter seats are all used, the price will go up and stay at $33/year.
Last updated: September 7, 2024
In this short tutorial, let’s convert a Java Iterable object into a Stream and perform some standard operations on it.
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.
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"));
}
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.