【问题标题】:Using lambda to filter stream and throw an exception使用 lambda 过滤流并抛出异常
【发布时间】:2016-08-28 08:05:17
【问题描述】:

目前我们使用Set<String> clients 实现的基本方法如下 -

if (clients.isEmpty()) {
    throw new InvalidClientException();
}

for (String client : clients) {
    if (!myMay.containsKey(client)) {
        throw new InvalidClientException(client);
    }
}

我尝试使用 lambda 表达式将其转换如下 -

clients.stream().filter(client -> !myMay.containsKey(client) || clients.isEmpty())
            .forEach(InvalidClientException::new);

但这似乎不是以同样的方式工作,参数化的构造函数调用在这里错过了吗?

【问题讨论】:

    标签: java exception lambda java-stream


    【解决方案1】:

    首先,如果集合为空,则传递给 forEach 的 lambda 不会被执行:空流是空的,过滤它不会向其中添加任何元素。仅可能删除一些。

    其次,lambda 创建一个异常。但它不会抛出它。

    你可以使用

    if (clients.isEmpty() || clients.stream().anyMatch(client -> !myMay.containsKey(client))) {
        throw new InvalidClientException();
    }
    

    编辑:我错过了您想将不在集合中的(第一个?)客户端传递给异常的事实。为此,您可以这样做

    if (clients.isEmpty()) {
        throw new InvalidClientException();
    }
    
    clients.stream()
           .filter(client -> !myMay.containsKey(client))
           .findAny() // or .findFirst()
           .ifPresent(client -> {
               throw new InvalidClientException(client);
           });
    

    这仅在异常是运行时异常时才有效,因为您不能从消费者抛出已检查异常。如果它是一个已检查的异常并且您确实希望将其保持为已检查的异常,则可以使用

    if (clients.isEmpty()) {
        throw new InvalidClientException();
    }
    
    Optional<String> wrongClient = 
        clients.stream()
               .filter(client -> !myMay.containsKey(client))
               .findAny();
    if (wrongClient.isPresent()) {
        throw new InvalidClientException(wrongClient.get());
    }
    

    【讨论】:

    • 哦,在流式传输时无法使用过滤器并抛出异常?
    • 这里也怎么处理throw new InvalidClientException(client)
    • 你不想稀释。您想查找流的元素是否不在 myMay 集中。这就是anyMatch() 所做的。为不在集合中的每个元素抛出异常没有多大意义,因为一旦抛出异常,循环就会停止。
    • 我的意思是对 InvalidClientException(client) 的参数化调用,我需要传递无效的客户端名称
    • 对于ifPresent 部分,更新版本似乎无法在我的 IDE 上运行
    猜你喜欢
    • 1970-01-01
    • 2017-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-16
    • 2014-10-19
    相关资源
    最近更新 更多