Unwrap an Optional only if it is present

后端 未结 2 1723
执念已碎
执念已碎 2021-02-14 01:27

So currently I have

String uri = website.getUri();
Optional pageDetail = webClient.getDetailOfUri(uri);
String displayName;
String description;         


        
相关标签:
2条回答
  • 2021-02-14 02:07

    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.

    0 讨论(0)
  • 2021-02-14 02:25

    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.

    0 讨论(0)
提交回复
热议问题