Extracting first defined value(if any) from sequence of suppliers of optional values

Viewed 105

Given a sequence of Supplier<Option<T>> -- e.g., a list of method references -- what's the idiomatic way to get the first defined result, if any? Ideally without invoking any more suppliers after the first successful result.

What I have now is:

Stream<Supplier<Option<Foo>>> suppliers = Stream.of(
  bar::fooOption,
  baz::fooOption,
  qux::fooOption
);

Option<Foo> firstDefined = suppliers.map(Supplier::get)
  .find(Option::isDefined)
  .flatMap(Function.identity());

but it seems like there ought to be a way to flatmap that even flatter.

2 Answers
Related