Java 我们可以通过流和映射抛出两个异常吗?
实际上,我想抛出两个异常作为检查两个条件的一部分。但是想知道如何在流化和映射之后抛出这些异常 这是要使用Streams转换为Java-8的代码Java 我们可以通过流和映射抛出两个异常吗?,java,java-8,Java,Java 8,实际上,我想抛出两个异常作为检查两个条件的一部分。但是想知道如何在流化和映射之后抛出这些异常 这是要使用Streams转换为Java-8的代码 for(GroupCallCenter existingGroupCall : group.getGroupCallCenters()) { if(!existingGroupCall.getCallCenter() .getId().equals(accountCallCenterResource.getC
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
是最终的或有效的最终的,才能在stream方法中使用它
有关更详细的了解,请参阅,一次只能引发一个异常。但是,您可以创建一个包含错误的列表并返回该列表,或者将其添加到您提出的异常中,因为您的问题不清楚。你是在问关于将循环转换为流操作的问题吗?是的,我正在尝试将循环转换为流并抛出异常,因此你的代码很难阅读,没有随意的缩进。也许您想修复它。转换为的原因是什么?为什么不直接
group.getGroupCallCenters().forEach()
?它提供了什么好处?不应该这样使用。@Nikolas,我们甚至可以使用组。getGroupCallCenters().forEach()
。但他想用流来使用它。所以我又这样保存了一次,有什么好处?你可能想通过阅读来证明为什么你的方法违反了原则。我不理解你的愤怒——你有理由因为不同意我的评论而否决我的投票吗?