Streams - 过滤所有不抛出异常

ibe*_*beu 2 java exception list java-8 java-stream

假设我有一个Reports流,我有一个方法可以检查用户是否有权读取每个报告.如果用户没有权限,此方法将抛出异常

checkReadAuthorization(Report report) throw AccessViolationException;
Run Code Online (Sandbox Code Playgroud)

有没有办法过滤掉此方法引发异常的所有报告?就像是:

reports.stream()
.filterThrowingException(this::checkReadAuthorization);
Run Code Online (Sandbox Code Playgroud)

现在我有一个函数,如果抛出异常则返回true或false但是我想知道是否有更好的方法来实现这个

private boolean checkAuthorization(Report report) {
    try {
        checkReadAuthorization(report);
        return true;
    } catch(AccessViolationException ex) {
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我在这样的过滤器中使用它

return dossiers.stream()
    .filter(this::checkAuthorization)
    .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

Nik*_*las 5

filterThrowingException当前的Stream-API中没有类似" "的内容.您只能做出保留或过滤掉内部Report使用try-catch的决定Stream::filter:

List<Report> filtered = list.stream().filter(report -> {
    try {
        this.checkAuthorization(report);
    } catch (AccessViolationException ex) {
        return false;
    }
    return true;
}).collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

就个人而言,我建议更改方法的界面checkReadAuthorization以返回boolean指示输入是否有效.

private boolean checkReadAuthorization(Report report) { /* ... */ }
Run Code Online (Sandbox Code Playgroud)

此结果可用作过滤器中的谓词.

List<Report> filtered = list.stream()
                            .filter(this::checkReadAuthorization)
                            .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

简介:更好地改变验证类和方法的设计,而不是尝试使用Stream-API来调整非最佳的.

  • 此外,这是一个很好的做法,因为它避免了多行lambda表达式. (3认同)