在这种简单
doStuff方法的情况下,
void您只关心异常,可以使事情保持简单:
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; });但是,如果您的要求更加复杂,并且您更喜欢使用标准库,
CompletableFuture则可以代表“成功或失败”(尽管有一些缺陷):
public static void doStuffonList(List<MyObject> 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); });}


