3

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");
}
ekjcfn3902039
  • 1,471
  • 1
  • 19
  • 43

1 Answers1

7

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.

jannis
  • 4,308
  • 1
  • 20
  • 44