Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 throw exception if stream returns no results [duplicate]

Tags:

java

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");
}
like image 521
ekjcfn3902039 Avatar asked Oct 26 '25 17:10

ekjcfn3902039


1 Answers

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.

like image 190
jannis Avatar answered Oct 29 '25 06:10

jannis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!