Zaryab
Zaryab

Reputation: 11

How to take advantage of lambda expression with optionals

I am trying to find a clean and code efficient way to apply the transform method in guava optional to create an object, I am working with Java 8 with Guava.

In one place of the code, I have an optional created . Optional<Object> optional = Optional.of(objFromDatabase)

And in another area I am trying to create a new object with this optional. The best thing I could think of is

    if (optional.isPresent()) {
        Object obj = optional.get();
        NewObject newObj = obj.createNewObj(); //throws IOException, newobj to be returned
    } else { throw new IOException() }

But this is cumbersome, and I'm hoping to learn a bit more about optionals and lambda expressions.

Any good ideas out there?

Upvotes: 1

Views: 216

Answers (4)

Olivier Gr&#233;goire
Olivier Gr&#233;goire

Reputation: 35457

No one really gave a code answer, so here's one.

First, create a method that maps the object and handles the checked exception (by wrapping it in a unchecked exception).

private NewObject uncheckedCreateNewObject(Object o) {
  try {
    return o.createNewObject();
  } catch (IOException e) {
    throw new UncheckedIOException(e);
  }
}

Then, just do a normal mapping:

NewObject newObject = Optional.of(objFromDatabase).toJavaUtil()
  .map(this::uncheckedCreateNewObject)
  .orElseThrow(IOException::new);

Upvotes: 3

Grzegorz Rożniecki
Grzegorz Rożniecki

Reputation: 28015

If you really don't want to swap Guava Optional to JDK's Optional (but you should), you can use helper toJavaUtil() method and operate on its API:

guavaOptional.toJavaUtil()
    .map(obj -> obj.createNewObj())
    .orElseThrow(IOException::new);

EDIT: If your createNewObj() method throws checked exception (here: IOException), you obviously won't be able to put in in lambda expression without wrapping it with unchecked exception first (eg. UncheckedIOExcpetion).

Upvotes: 1

Jun Bach
Jun Bach

Reputation: 111

There is orEsleThrow method using with Optional. Try this:

NewObject obj = Optional.ofNullable(objFromDatabase)
  .map(o -> o.createNewObj())
  .orElseThrow(IOException::new)

Upvotes: 0

Roman Dzhadan
Roman Dzhadan

Reputation: 168

If it's possible, try to get rid from Guava's Optional`s in your codebase. They was designed before Oracle's Optional. In this case will be easier to use Stream API. It's a bad practice to mix both of them.

Upvotes: 1

Related Questions