Extracting the first defined value (if any) from a sequence of optional value providers

Given a sequence Supplier<Option<T>>

- like a list of method references - what's the idiomatic way to get the first defined result, if any? Ideally, no additional suppliers are involved after the first successful outcome.

Now I have:

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 should be a way to flatmap that 💩 is even flatter.

+3


source to share


2 answers


I can only see an equal number of steps alternative solution like yours.

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

      



If you can use simple map

instead flatMap

, use instead as it will usually be faster, especially in multi-valued monadic containers. Probably not much of a difference, although for 0/1 rated monuments like Option

maybe the other way around, it might be slower in this case as it creates extra Option

.

+2


source


You want flatMap

:)



 suppliers.flatMap(_.get).headOption

      

+2


source







All Articles