javanulloption-type

Use Optional instead of null check


I have to check if an attribute of an object is null or not. Depending on the above check I have to update another attribute in the same object. Is it possible to use Optional class and its methods to replace null checks?

if(userData.getSubscription()==null){
    userData.setFees(Enum.ZERO);
} else {
    userData.setFees(Enum.HUNDRED);
}

Let me know if this can be replaced with a single line using Java 8 Optional class or other features.


Solution

  • Maybe you want: userData.setFees(Objects.isNull(userData.getSubscription()) ? Enum.ZERO : Enum.HUNDRED)