I am curious if it's possible to use orElseThrow() in the following situation or if there a more Java 8 way to do the equivalent of this as a 1-liner?
Collection<Foo> foo = blah.stream().filter(somePredicate).collect(Collectors.toList());
if (foo.isEmpty()) {
throw new Exception("blah");
}
You could try this:
Collection<Foo> foo = blah.stream().filter(somePredicate)
.collect(Collectors.collectingAndThen(Collectors.toList(), Optional::of))
.filter(l -> !l.isEmpty())
.orElseThrow(() -> new Exception("blah"))
Note that comparing to your code this allocates an extra Optional instance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With