Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Optional to boolean in functional style

I just wanted to return a boolean from an Optional object by doing a check on the getProductType() on the ProductDetails object as shown below:

public boolean isElectronicProduct(String productName) {
    Optional<ProductDetails> optProductDetails = findProductDetails(productName);
    if(optProductDetails.isPresent()) {
        return optProductDetails.get().getProductType() == ProductType.ELECTRONICS;
    }
    return false;
}

Intellij complains stating that the above code can be replaced in functional style, is there really any way to simplify the above Optional object and return a boolean?

like image 540
developer Avatar asked Oct 25 '18 16:10

developer


People also ask

How do you convert boolean to Boolean?

Use the valueOf() method to convert boolean value to Boolean. Firstly, let us take a boolean value. boolean val = false; Now, to convert it to Boolean object, use the valueOf() method.

What is difference between isPresent and ifPresent?

isPresent() method returns true if the Optional contains a non-null value, otherwise it returns false. ifPresent() method allows you to pass a Consumer function that is executed if a value is present inside the Optional object. It does nothing if the Optional is empty.

How do you handle optional empty?

Optional class in Java is used to get an empty instance of this Optional class. This instance do not contain any value. Parameters: This method accepts nothing. Return value: This method returns an empty instance of this Optional class.

How do you know if Boolean is optional?

Optionals no longer implicitly evaluate to true when they have a value and false when they do not, to avoid confusion when working with optional Bool values. Instead, make an explicit check against nil with the == or != operators to find out if an optional contains a value.


1 Answers

Change this:

if(optProductDetails.isPresent()) {
    return optProductDetails.get().getProductType() == ProductType.ELECTRONICS;
}
return false;

To:

return optProductDetails
      .filter(prodDet -> prodDet.getProductType() == ProductType.ELECTRONICS)  // Optional<ProductDetails> which match the criteria
      .isPresent();   // boolean

You can read more about functional-style operations on Optional values at: https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html

like image 73
lealceldeiro Avatar answered Nov 15 '22 21:11

lealceldeiro