我正在使用函数调用过滤器,如下面的流 -
list.stream()
.filter(a -> !StringUtils.isEmpty(a.getProp1()))
.filter(a -> !a.getProp1().matches(“(.*)xyz"))
.filter(a -> {try {
return isValid(a.getProp1());
} catch (javax.naming.NamingException e) {
logger.error("Error");
}
})
我提到question但我不想在catch块中抛出异常。我只想记录它。
我想保留在调用isValid(a)时返回true的记录,然后能够在如下的HashSet中收集它 -
// .collect(Collectors.toCollection(HashSet::new));
从代码中可以看出这一点,但我是java 8的新手并且还在学习概念。请原谅任何天真的代码。谢谢你的帮助。
答案 0 :(得分:2)
在进行过滤时,如果isValid
方法抛出javax.naming.NamingException
,除了记录异常外,您可能还想返回false
:
Set<Whatever> result = list.stream()
.filter(a -> !StringUtils.isEmpty(a.getProp1()))
.filter(a -> !a.getProp1().matches("(.*)xyz"))
.filter(a -> {
try {
return isValid(a.getProp1());
} catch (javax.naming.NamingException e) {
logger.error("Error");
return false;
}})
.collect(Collectors.toCollection(HashSet::new));
这是因为传递给Predicate
方法的Stream.filter
参数必须始终返回一个布尔值,无论它是否捕获了异常。