How to reduce a stream of Futures in Java?
You could extract the value from the future first, and then filter out null:
Integer result = stream
.map(future -> {
try {
return future.get();
} catch (InterruptedException | ExecutionException e) {
}
return null; })
.filter(Objects::nonNull)
.reduce(sum)
.orElse(0);
One of the ways to simplify it could be:
void reduceImpl(Stream<Future<Integer>> stream) {
Optional<Integer> integerOptional = stream
.map(this::transform)
.filter(Objects::nonNull)
.reduce(Integer::sum);
}
private Integer transform(Future<Integer> future) {
try {
return future.get();
} catch (InterruptedException | ExecutionException e) {
return null; // should ideally be handled properly
}
}
You can do that using flatMap
:
public static void main(String[] args) {
Stream<Future<Integer>> yourStream = null;
int sum = yourStream.flatMap(YourClass::unpack)
.mapToInt(Integer::intValue)
.sum()
.orElse(0);
}
public static <T> Stream<T> unpack(Future<T> future) {
try {
return Stream.of(future.get());
} catch (InterruptedException e) {
return Stream.empty();
} catch (ExecutionException e) {
return Stream.empty();
}
}