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.
1 2 3 4 5 6 7 8 9 10 11 12 13 | class SomeThirdPartyCodes { private List<String> someData; public SomeThirdPartyCodes(List<String> someData) { super(); this.someData = someData; } public Iterator<String> getIterator() { return this.someData.iterator(); } } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | package com.turreta.iterator; import java.util.Iterator; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport; public class Iterator2Stream { public static void main(String[] args) { // Test data List<String> data = Stream.of("a", "b", "c").collect(Collectors.toList()); // Instantiating the third-party code SomeThirdPartyCodes iO = new SomeThirdPartyCodes(data); // Get the Iterator from the third-party code Iterator<String> iterator = iO.getIterator(); // We use this functional interface Iterable<String> iterable = () -> iterator; /* * We pass this functional interface to the StreamSuport.stream(...). The second parameter indicates whether to * use parallel processing or not */ Stream<String> streamData = StreamSupport.stream(iterable.spliterator(), false); streamData.forEach(System.out::println); } } |
Then, we use Java Iterable, which we supply to the StreamSupport class. When we run the codes, we get the following results.
1 2 3 | a b c |
This post is (now) part of a reboot Java tutorial.