Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unwrap an Optional only if it is present

So currently I have

String uri = website.getUri();
Optional<PageDetail> pageDetail = webClient.getDetailOfUri(uri);
String displayName;
String description;
if (pageDetail.isPresent()) {
    displayName = pageDetail.get().getName();
    description = pageDetail.get().getDescription();
} else {
    displayName = uri;
    description = "";
}

I am calling the getDetailOfUri(uri) method, which returns an Optional<PageDetail>, and I would like to set the strings displayName and description to the values of the PageDetail object's fields, if it is present. Otherwise, I would like to set it to some default values.

My question is, is there a better way to rewrite this? My current code seems a bit long and tedious, and I would like to know if there is a more concise way of doing this.

like image 917
yiwei Avatar asked Aug 28 '15 18:08

yiwei


People also ask

How do you unwrap Optional value?

Unwrap an optional type with optional binding Then in the if-let block, the optional value password is unwrapped and assigned to the variable unwrappedpass only if the optional value password is not nil. unwrappedpass now contains the unwrapped value and can be used within the block's scope.

Which method of the Optional class can be used to unwrap an Optional instance?

static <T> Optional<T> empty() Returns an empty Optional instance.

How do I make Optional isPresent false?

If you just want an Optional returning false for isPresent() , you don't need to mock the Optional at all but just create an empty one. Of course this test only tests that the mock object actually returns the stubbed return value, but you get the idea.

What does Optional get return if empty?

In Java, the Optional object is a container object that may or may not contain a value. We can replace the multiple null checks using the Optional object's isPresent method. The empty method of the Optional method is used to get the empty instance of the Optional class. The returned object doesn't have any value.


2 Answers

Use Optional#orElseGet that takes a Supplier:

// Reference to the constructor, but you could use a Factory, etc.
// All you need is a method that returns a PageDetail
// See the Javadoc and http://www.byteslounge.com/tutorials/java-8-consumer-and-supplier
Supplier<PageDetail> emptySupplier = PageDetail::new;

pageDetail = pageDetail.orElseGet(emptySupplier);
// works the same
//pageDetail = pageDetail.orElseGet(() -> new PageDetail());

String displayname = pageDetail.getName();
String uri = pageDetail.getUri();

orElseGet will create an empty PageDetail only if the Optional has a null value. This keeps your code resource efficient.

Editable/compilable sample : https://ideone.com/9h1Ntg

Edit: Thanks everybody for the feedback! I was actually adding orElseGet which I find better. I also fixed the code to unwrap the Optional so pageDetail ends being an actual PageDetail instance.

Edit 2: Added different syntax example and editable/compilable example.

like image 135
pyb Avatar answered Oct 18 '22 05:10

pyb


You could write:

String uri = website.getUri();
Optional<PageDetail> pageDetail = webClient.getDetailOfUri(uri);
String displayName = pageDetail.map(PageDetail::getName).orElse(uri);
String description = pageDetail.map(PageDetail::getDescription).orElse("");

If the Optional is not set, map will return the same unset Optional. Otherwise, it will map it to an Optional containing the result of getName(). Then we can use orElse to return a default value when the Optional is unset.

like image 35
Tunaki Avatar answered Oct 18 '22 05:10

Tunaki