4

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,673
  • 3
  • 29
  • 54

1 Answers1

10

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,843
  • 1
  • 23
  • 53