【问题标题】:Streams - Filter all not throwing exception流 - 过滤所有不抛出异常
【发布时间】:2018-08-09 11:32:30
【问题描述】:

假设我有一个报告流,并且我有一个方法可以检查用户是否有权阅读每个报告。如果用户没有权限,这个方法会抛出异常

checkReadAuthorization(Report report) throw AccessViolationException;

有没有办法过滤掉该方法引发异常的所有报告?比如:

reports.stream()
.filterThrowingException(this::checkReadAuthorization);

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

private boolean checkAuthorization(Report report) {
    try {
        checkReadAuthorization(report);
        return true;
    } catch(AccessViolationException ex) {
        return false;
    }
}

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

return dossiers.stream()
    .filter(this::checkAuthorization)
    .collect(Collectors.toList());

【问题讨论】:

  • 更好的方法是重构 checkReadAuthorization 以便它返回一些东西(例如布尔值)而不是抛出异常。

标签: java list exception java-8 java-stream


【解决方案1】:

在当前的 Stream-API 中没有像“filterThrowingException”这样的东西。您只能在Stream::filter 中使用try-catch 来决定保留或过滤Report

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

个人建议把checkReadAuthorization方法的接口改成返回boolean表示输入是否有效。

private boolean checkReadAuthorization(Report report) { /* ... */ }

这个结果可以用作过滤器中的谓词。

List<Report> filtered = list.stream()
                            .filter(this::checkReadAuthorization)
                            .collect(Collectors.toList());

总结:最好改变验证类和方法的设计,而不是尝试 Stream-API 来适应不是最优的。

【讨论】:

  • 另外,这是一个很好的做法,因为它避免了多行 lambda 表达式。
  • 我认为这已经足够了。无论如何,如果您使用的是外部函数,则无法更改它。我认为添加到流库中会是一件好事
【解决方案2】:

我会交换checkReadAuthorizationcheckAuthorization

private boolean checkAuthorization(Report report) 
{
    // put here the logic that checks for authorization, but without throwing exception
}

void checkReadAuthorization(Report report) throw AccessViolationException
{
    if (!checkAuthorization(report)) {
        throw new AccessViolationException ();
    }
}

这样您就不会使用异常作为条件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-29
    • 2013-09-07
    • 1970-01-01
    • 2017-04-20
    • 1970-01-01
    • 1970-01-01
    • 2018-07-07
    相关资源
    最近更新 更多