Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Check Not Null for a number, else assign default string value

I am looking for a way to set the default value of a variable depending on whether a value is null or not.

The value in question is a double, and the default value (if that value is null) should be a string.

I tried using the following way but it failed because .orElse expects a double (aka same data type as "value"). Is there any Java methods that I can use to achieve that?

Double value = 8.0;
Optional.ofNullable(value).orElse("not found")
like image 260
coffeeak Avatar asked Jan 01 '23 19:01

coffeeak


2 Answers

You are not far, just map the value:

String strDouble = Optional.ofNullable(value).map(Objects::toString).orElse("not found");
like image 127
A Monad is a Monoid Avatar answered Jan 08 '23 02:01

A Monad is a Monoid


Since the left side of the the assignment operator can be either a Double or a String, the best that can be done is to specify its type as Object.

This will work:

Object value2 = Optional.<Object>ofNullable(value).orElse("not found");

(i.e. The only shared class in the class hierarchy for Double and String is Object)

like image 32
StvnBrkdll Avatar answered Jan 08 '23 01:01

StvnBrkdll