0

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
Talenel
  • 422
  • 2
  • 6
  • 25
driftking9987
  • 1,673
  • 1
  • 32
  • 63

2 Answers2

1

There is no build in method because in Floating-point arithmetic NaN constant represents something which is undefined or unrepresentable. This is not the same as specific value like 0 or -1. See this question which explains what NaN is.

You should handle it yourself by writing the right logic in your own method, like you already did with the if statement.

Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
1

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.

tobias_k
  • 81,265
  • 12
  • 120
  • 179