尝试根据条件应用多个过滤器,伪代码是:
if TypeA exception
then throw TypeA Exception
if TypeB
then throw TypeB Exception
else TypeC Exception.
我不知道如何使用基于条件的过滤器来做到这一点:
List<InvalidArgumentException> invalidEx = e.getInvalidException();
return invalidEx.stream()
.filter (ic -> {
if(ic.getInvalidExcepType().equals(ExceptionType.TypeA)) {
return (RuntimeException) new TypeAException(e);
} else if (ic.getInvalidExcepType().equals(ExceptionType.TypeB))
return (RuntimeException) new TypeBException(e);
}).orElse (new TypeCException(e));
最佳答案
您需要使用 map
,而不是使用仅返回 Stream
中与给定谓词匹配的所有元素的 filter
:
return invalidEx.stream()
.map(ic -> {
if(ic.getInvalidExcepType().equals(ExceptionType.TypeA)) {
return (RuntimeException) new TypeAException(e);
} else if (ic.getInvalidExcepType().equals(ExceptionType.TypeB)) {
return (RuntimeException) new TypeBException(e);
} else {
return new TypeCException(e);
}
}).collect(Collectors.toList());
(或其他一些终端操作)
关于java - 如何创建基于条件的多重过滤器并返回非 boolean 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54298969/