Let\'s say I have a method which throws a runtime exception. I\'m using a Stream
to call this method on items in a list.
class ABC {
public voi
In this simple case where the doStuff
method is void
and you only care about the exceptions, you can keep things simple:
myObjs.stream()
.flatMap(o -> {
try {
ABC.doStuff(o);
return null;
} catch (RuntimeException ex) {
return Stream.of(ex);
}
})
// now a stream of thrown exceptions.
// can collect them to list or reduce into one exception
.reduce((ex1, ex2) -> {
ex1.addSuppressed(ex2);
return ex1;
}).ifPresent(ex -> {
throw ex;
});
However, if your requirements are more complicated and you prefer to stick with the standard library, CompletableFuture
can serve to represent "either success or failure" (albeit with some warts):
public static void doStuffOnList(List myObjs) {
myObjs.stream()
.flatMap(o -> completedFuture(o)
.thenAccept(ABC::doStuff)
.handle((x, ex) -> ex != null ? Stream.of(ex) : null)
.join()
).reduce((ex1, ex2) -> {
ex1.addSuppressed(ex2);
return ex1;
}).ifPresent(ex -> {
throw new RuntimeException(ex);
});
}