Search code examples
javastreamfuture

How to convert Future to Stream without calling Future.get?


Suppose I have a list of Future objects.List<Future<List<Data>>> futures. I want to convert it to one Stream<Data>.
Apparently I can do like this:

List<Data> list=new ArrayList();
for(Future future:futures){
    list.addAll(future.get());
}
return list.steam();

But this method have to wait for all futures to return before it can return the Stream.
I want to make it work like a pipeline, the upper layer extract data from the stream and process it as needed, don't have to wait all futures to finish.


Solution

  • Do you want something like this?

    List<Future<List<Data>>> futures;
    return futures.stream().flatMap(future->future.get().stream());
    

    map() and flatMap() are run only when actually using them.

    This way, you won't avoid the get() call but it is only called at the moment you are using it.