为了账号安全,请及时绑定邮箱和手机立即绑定

如果过滤器返回大小为 0 的列表,则抛出异常

如果过滤器返回大小为 0 的列表,则抛出异常

猛跑小猪 2023-08-23 17:06:38
在下面的代码中:myList.stream()     .filter(item -> someMethod(item))     .map(item -> doSomething(item))     .collect(Collectors.toList());RuntimeException如果过滤器的结果是大小为 0 的列表(即没有项目通过过滤器),我该如何抛出 a ?
查看完整描述

2 回答

?
aluckdog

TA贡献1847条经验 获得超7个赞

您可以使用collectingAndThen:


   myList.stream()

            .filter(item -> someMethod(item))

            .map(item -> doSomething(item))

            .collect(Collectors.collectingAndThen(Collectors.toList(), result -> {

                if (result.isEmpty()) throw new RuntimeException("Empty!!");

                return result;

            }));


查看完整回答
反对 回复 2023-08-23
?
慕桂英3389331

TA贡献2036条经验 获得超8个赞

由于没有直接的方法如何检查 Java 8 Stream 是否为空?,更好的代码是:

List<SomeObject> output = myList.stream()

        .filter(item -> someMethod(item))

        .map(item -> doSomething(item))

        .collect(Collectors.toList());

if (!myList.isEmpty() && output.isEmpty()) {

    throw new RuntimeException("your message");

另一种替代方法是使用noneMatch, 在执行前进行验证,例如:


if (myList.stream().noneMatch(item -> someMethod(item))) {

    throw new RuntimeException("your message");

}


查看完整回答
反对 回复 2023-08-23
  • 2 回答
  • 0 关注
  • 113 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信