Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating inputs using Optional

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?

like image 678
a13e Avatar asked Oct 17 '22 08:10

a13e


2 Answers

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);
like image 168
Naman Avatar answered Nov 15 '22 06:11

Naman


Try this

Optional.ofNullable(each.getQty()).map(Integer::valueOf).orElse(0)
like image 37
Hadi J Avatar answered Nov 15 '22 07:11

Hadi J