java - 如何创建基于条件的多重过滤器并返回非 boolean 值?

标签 java

尝试根据条件应用多个过滤器,伪代码是:

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/

相关文章:

java - 64 位十六进制随机数值给出 16 个字符,有时给出 15 个字符,为什么?

java - Jaspersoft 工作室 : UTF-8 encoding issue

java - Desfire - Ndef 应用程序命令 : get security exception

java - 查找单词/字符串中的字符序列并用其出现次数替换

java - 从Sybase ASE 15.7数据库读取存储过程源代码

java - 使用 Spring 的 Google App Engine GAE MemcacheService 单例注入(inject)

java - 如何在类路径上查找属性文件?

Java CRUD 应用程序卡在 "Update"上!

java - 我需要将哪些 Apache Commons IO jar 添加到我的 Android lib 文件夹中?

java - 单击按钮时,应用程序数据库崩溃