java - 我们可以通过 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());
}
}
解决方案
您可以只应用简单的流 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
是最终的或有效的最终才能在流方法中使用它。
更详细的了解可以参考这个
推荐阅读
- scala - 解构自定义类
- javascript - 无法使用 JSON.parse 解析字符串数组
- objective-c - 我可以在静态库中扩展 NSString 类并在带有 Swift 的 App 中使用它吗?
- ios - 链接器命令失败,退出代码为 1——Firebase
- fonts - 同一浏览器上的相同字体在不同计算机上显示不同
- c# - ASP.NET Web Api 返回 HTML 内容
- css - 在灵活的子孙之间创造空间
- apache-tika - Apache Tika - .doc 文件中的段落中断
- unity3d - 动画是附加到装备(骨架)还是网格上?
- html - 如何删除导航栏和下拉菜单之间的空间