我很好奇是否可以在以下情况下使用 orElseThrow() ,或者是否有更多 Java 8 方法来执行与 1-liner 相同的操作?
Collection<Foo> foo = blah.stream().filter(somePredicate).collect(Collectors.toList());
if (foo.isEmpty()) {
throw new Exception("blah");
}
你可以试试这个:
Collection<Foo> foo = blah.stream().filter(somePredicate)
.collect(Collectors.collectingAndThen(Collectors.toList(), Optional::of))
.filter(l -> !l.isEmpty())
.orElseThrow(() -> new Exception("blah"))
请注意,与您的代码相比,这会分配额外的Optional
实例。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)