Aggregate runtime exceptions in Java 8 streams

后端 未结 4 728
北荒
北荒 2021-01-30 22:49

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         


        
4条回答
  •  迷失自我
    2021-01-30 23:30

    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);
                });
    }
    

提交回复
热议问题