Home > Blockchain >  How to pass an Array as a parameter to a Function/Bifunction?
How to pass an Array as a parameter to a Function/Bifunction?

Time:07-16

I need to pass an array as parameter into a BiFunction.

Use case :

Calculate the Euclidean Distance of 2 coordinates given in an array. coordinate1 and coordinate2 are an array.

The below trial, makes the intent clearer.

BiFunction<Integer, Integer, Double> euclideanDistance =
   (Integer[] x, Integer[] y) -> Math.sqrt(Math.pow(x[0] - y[0], 2)   Math.pow(x[1] - y[1], 2));

But the compiler complains :

incompatible types:
incompatible parameter types in lambda expression :
Expected Integer but found Integer[]

CodePudding user response:

You can use any reference type as a parameter to the Function. Your BiFunction should take two int[] as it's input and return a Double. So, the target type of the assignment should be something like this.

BiFunction<int[], int[], Double> euclideanDistance =
                (int[] x, int[] y) -> Math.sqrt(Math.pow(x[0] - y[0], 2)   Math.pow(x[1] - y[1], 2));

CodePudding user response:

The types of function (Integer) you've defined don't match expected arguments of your lambda expression (Integer[]).

And there's no need to use arrays of wrapper type, as well as no need to resort to sqrt() and pow() since we have hypot() method in the Math class which does exactly what is needed:

Returns: sqrt(x2 y2) without intermediate overflow or underflow

So the function for calculating the Euclidean distance can be written like this:

BiFunction<int[], int[], Double> euclideanDistance =
    (int[] x, int[] y) -> Math.hypot(x[0] - y[0], x[1] - y[1]);
  • Related