Is there any lambda expression through which I can replace the NaN
value to 0
or -1
while passing it to a function?
I know I can put a check for NaN
like this:
if (Double.isNaN(variable_name))
{
// make it 0 or -1
}
But I want to do it using lambda expression like
function_to_called("variable_string", variable_double); // have a check if variable double is NaN
You could just use a ternary ... ? ... : ...
instead of your if
check and make that a lambda
:
Function<Double, Double> deNan = n -> Double.isNaN(n) ? -1 : n;
However, while this is nice and short, this way you will have to call apply
on the Function
instead of being able to call the function directly, i.e. you'd have to do function_to_called("variable_string", deNan.apply(variable_double));
. So instead, you might just define it as a regular method instead of a lambda so you can use it as deNan(variable_double)
.
Also, as already noted, replacing NaN
with a "special" (or not-so-special) value like 0
or -1
might actually not be such a good idea. Instead, it might be better to filter out NaN
values entirely, or to handle them "properly", whatever that entails in your scenario.