Johannes
Johannes

Reputation: 2121

Optional / consuming optionals and returning another Optional

I'm running into a problem where I guess I would need something like orElseMap(...)/orElseFlatMap(...).

I'm consuming an optional from a method invocation. If that Optional is empty I want to retrieve another Optional from another method. Then I want to return an Optional describing if a value has been found through one of the two calls or not.

Am I just missing something?

So I want to do something like:

public Optional<Foo> getSomething()
{
  final Optional<Foo> foo = service.getFooFromBla()

  if (foo.isPresent())
    return foo;
  else
    return service.getFooFromBlubb();
}

I'm not really satisfied with the above solution, but maybe it's the only working thing right now. Usually if I want to unwrap I'm using map(...)/flatMap(...) in combination with orElse(...)/orElseGet(...), which is really concise.

but I'm missing the method orElseMap(...) and orElseFlatMap(...).

Upvotes: 2

Views: 301

Answers (2)

Johannes
Johannes

Reputation: 2121

Ah well, just found out that Java 9 added the or(...)-method which is precisely what I wanted (which is not available in Java 8, that's why I had no clue).

Upvotes: 3

Leviand
Leviand

Reputation: 2805

If you need to do that with Java8 : both orElse and orElseGet are returning a String , you can wrap them into an Optional, something like

public Optional<Foo> getSomething()
{
     return Optional.ofNullable(service.getFooFromBla().orElse(service.getFooFromBlubb()));
}

Upvotes: 1

Related Questions