Aggregate runtime exceptions in Java 8 streams

后端 未结 4 732
北荒
北荒 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:29

    The only possible way I can imagine is to map values in a list to a monad, that will represent the result of your processing execution (either success with value or failure with throwable). And then fold your stream into single result with aggregated list of values or one exception with list of suppressed ones from the previous steps.

    public Result doStuff(List list) {
         return list.stream().map(this::process).reduce(RESULT_MERGER)
    }
    
    public Result process(Object listItem) {
        try {
             Object result = /* Do the processing */ listItem;
             return Result.success(result);
        } catch (Exception e) {
             return Result.failure(e);
        }
    }
    
    public static final BinaryOperator> RESULT_MERGER = (left, right) -> left.merge(right)
    

    Result implementation may vary but I think you get the idea.

提交回复
热议问题