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?
Integer.parseInt(each.getQty())
is safe enough since if each.getQty
is null
, you would end up getting a NumberFormatException
and that should be the behavior when you're trying to parse a String to an Integer and are not certain of it.
On the other hand still, you can default to 0
for the value being null
as :
int quantity = Optional.ofNullable(each.getQty())
.map(Integer::parseInt)
.orElse(0);
similarily for amount
double amount = Optional.ofNullable(each.getPrice().getAmount())
.map(Double::parseDouble)
.orElse(Double.NaN);
Try this
Optional.ofNullable(each.getQty()).map(Integer::valueOf).orElse(0)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With