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

在下面的代码中:

myList.stream()
    .filter(item -> someMethod(item))
    .map(item -> doSomething(item))
    .collect(Collectors.toList());

RuntimeException如果过滤器的结果是大小为 0 的列表(即没有项目通过过滤器),我该如何抛出 a ?


猛跑小猪
浏览 115回答 2
2回答

aluckdog

您可以使用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;            }));

慕桂英3389331

由于没有直接的方法如何检查 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");}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java