【问题标题】:Can we throw two Exceptions by Streaming and mapping?我们可以通过 Streaming 和 mapping 抛出两个异常吗?
【发布时间】:2019-04-15 13:12:25
【问题描述】:

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

这是使用 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());   
       }
   }

【问题讨论】:

  • 一次只能抛出一个异常。但是,您可以构建一个包含错误的列表并将其返回,或者将其添加到您抛出的异常中
  • 您的问题不清楚。您是在询问将循环转换为流操作吗?
  • 是的,我正在尝试将循环转换为流并在那里抛出异常
  • 如果没有随意的缩进,您的代码很难阅读。也许你想修复它。
  • 转换为java-stream的原因是什么?

标签: java java-8


【解决方案1】:

您可以像下面这样应用简单的 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 是最终的或有效地最终的,才能在流方法中使用它。

更详细的了解可以参考this

【讨论】:

猜你喜欢
  • 2022-01-02
  • 2011-03-22
  • 1970-01-01
  • 2020-04-24
  • 1970-01-01
  • 2012-02-09
  • 1970-01-01
  • 1970-01-01
  • 2015-02-13
相关资源
最近更新 更多