Java, Software Development

Java 8 – Convert Iterator to Stream Using StreamSupport

Although not a common scenario, some libraries return Iterators instead of Stream or Collection objects. Why? Because they can. If the Java libraries you are using have methods that return Iterator objects, this will show how to convert Iterator to Stream using StreamSupport.

Java Iterator Only

Consider the following codes. Suppose they belong to a third-party library and, therefore, we cannot change the codes to suit our needs.

As we can see, to get the contents of the variable someData, we need to go through an Iterator. There is no other way except via the Reflection API, but we may not want to keep the codes simple and maintainable.

Use Java StreamSupport To Convert Iterators To Stream

To achieve our goal in this post, we will use the Java StreamSupport class to create Stream objects. Consider the following codes. So, we have a list of strings and pass them to a method that performs some operation on the data. Then, we retrieve the result using another method that returns an Iterator object.

Then, we use Java Iterable, which we supply to the StreamSupport class. When we run the codes, we get the following results.

This post is (now) part of a reboot Java tutorial.

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.

You Might Also Like