Java, Software Development

Java 8 – Convert Iterator to Stream Using StreamSupport

java Sort Enum Properties Monitor Directory File Lambda Expression parameter return types Validate XML String XSD ExecutorService AutoCloseable Try-With-Resources Convert LocalDateTime OffsetDateTime Run Codes Before Shutdown XML Tag Lambda PostgreSQL JDBC invoke JavaScript Applet SFTP Batch hang block main thread MySQL JDBC try-with-resources delete Unencrypted SoapFault Apache CXF Remove XML Element XSLT skip execute finally public static void main constructor fields Eclipse convert Iterator Stream StreamSupport XMLEncoder XMLDecoder rename P6Spy JDBC Example PDF Version JasperReports Run from Ant iReport Page Numbers Count entities persistence context hibernate

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? Please visit our Facebook page!

You Might Also Like