首页 > 解决方案 > 我们可以通过 Streaming 和 mapping 抛出两个异常吗?

问题描述

实际上,我想抛出两个异常作为检查两个条件的一部分。但是想知道如何在流式传输和映射后抛出这些异常。

这是使用 Streams 转换为 Java-8 的代码

  for(GroupCallCenter existingGroupCall : group.getGroupCallCenters())
   {
        if(!existingGroupCall.getCallCenter()
          .getId().equals(accountCallCenterResource.getCallCenterId())) 
            {
             if(!accountCallCenterResource.getValidity().getEffectiveStarting().isAfter(existingGroupCall.getExpirationDate())&&!existingGroupCall.getEffectiveDate().isAfter(accountCallCenterResource.getValidity().getExpiresAfter())) 
               {
                 throw new ApiException(ApiErrorCode.DEFAULT_400, "Group call 
                     center already exist for that period");
                  }
       }
  else {
         throw new DuplicateException(ApiErrorCode.DUPLICATE, 
         existingGroupCall.getId());   
       }
   }

标签: javajava-8

解决方案


您可以只应用简单的流 forEach,如下所示:

group.getGroupCallCenters().stream().forEach((existingGroupCall) ->
           {
               if(!existingGroupCall.getCallCenter()
              .getId().equals(accountCallCenterResource.getCallCenterId())) 
             {
               if 
              (!accountCallCenterResource.getValidity().getEffectiveStarting()
                    .isAfter(existingGroupCall.getExpirationDate())
                    && !existingGroupCall.getEffectiveDate()                      

       .isAfter(accountCallCenterResource.getValidity().getExpiresAfter())) 
                   {
               throw new ApiException(ApiErrorCode.DEFAULT_400, "Group call center already exist for that period");
                      }
           }
            else {
                throw new DuplicateException(ApiErrorCode.DUPLICATE, 
          existingGroupCall.getId());   
                }
            });

您没有提及accountCallCenterResource代码中的对象是什么。您必须确保它accountCallCenterResource是最终的或有效的最终才能在流方法中使用它。

更详细的了解可以参考这个


推荐阅读