Validating inputs using Optional

Aniruddha Tekade :

I have a CreateOrder instance which has some String, Integer and Double states in it. When I create an object for CreateOrder in my JUnit test and send it over, I am able to validate String attributes but not Integer using Optional API as follows -

String aoid = Optional.ofNullable(createOrder.getAltorderid()).orElse("");

int quantity = Integer.parseInt(each.getQty());
double amount = Double.parseDouble(each.getPrice().getAmount());

Like for aoid, I also want to user ofNullable() for integer but not able to figure it out how. My intention behind this is to make my code safe from NullPointerExceptions and hence I want to make the user of powerful Optional for Integer and Double. I am fairly new to Java 8 and getting confused if I should use OptionalInt or Optional<Integer>? If Optional<Integer>, how to use it like I have used for String?

Hadi J :

Try this

Optional.ofNullable(each.getQty()).map(Integer::valueOf).orElse(0)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=70274&siteId=1