I have a simple function, and simple question:
Do I need the first toList()
?
Arrays.stream(items)
// build task and submit to ExecutionService,
// which returns a Future
.map(item -> executeTask(item)) //Stream<Future<Result>>
// generate all the Futures, stash them in a collection,
// then wait for them to complete
.toList() //List<Future<Result>>
.stream() //Stream<Future<Result>>
//wait for result
.map(Future::get) //Stream<Result>
.toList();
More details, the function
- takes in an array of
items
- do some task on each
item
and submit the task to anExecutionService
, which returns aFuture
for eachitem
- wait for the result for all
items
before returning the list of results
My friend argues that we need that extra toList()
(after .map(item -> executeTask(item)
) operation because
Streams are lazily evaluated so the map() call isn't invoked until a terminal operation (toList()) is called. So we want to generate all the Futures, stash them in a collection, then wait for them to complete
But what I feel is that the function will work the same way even without that extra toList()
since we already have a toList()
after .map(Future::get)
.
So is it really needed?