Skip to content

Instantly share code, notes, and snippets.

@yradtsevich
Created June 6, 2017 12:11
Show Gist options
  • Save yradtsevich/5ab50d3e931ceca2d1c853db2959a5ae to your computer and use it in GitHub Desktop.
Save yradtsevich/5ab50d3e931ceca2d1c853db2959a5ae to your computer and use it in GitHub Desktop.
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
/**
* @author Yahor Radtsevich
*/
public class CompletableStream {
private static <T> Stream<T> toStream(CompletableFuture<Collection<T>> future) {
Iterator<T> asyncIterator = new AsyncIterator<>(future::join);
Iterable<T> iterable = () -> asyncIterator;
return StreamSupport.stream(iterable.spliterator(), false);
}
private static class AsyncIterator<T> implements Iterator<T> {
private final Supplier<Collection<T>> collectionSupplier;
Iterator<T> iterator;
AsyncIterator(Supplier<Collection<T>> collectionSupplier) {
this.collectionSupplier = collectionSupplier;
}
@Override
public boolean hasNext() {
return getIterator().hasNext();
}
@Override
public T next() {
return getIterator().next();
}
private Iterator<T> getIterator() {
if (iterator == null) {
iterator = collectionSupplier.get().iterator();
}
return iterator;
}
}
public static void main(String[] args) {
CompletableFuture<Collection<String>> future = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("COMPLETING FEATURE");
return Arrays.asList("a", "b", "c");
});
System.out.println("BEFORE");
Stream<String> targetStream = toStream(future);
System.out.println("AFTER");
targetStream.forEach(System.out::println);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment