Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a function as a parameter in java

Tags:

java

I have a matrix class and I want to create a function called map in this class, that looks something like this

  public void map(T fn) {
      //do something
   }

the idea behind the function is that as a parameter fn, which could be any method and apply this method to each number in the matrix.

the Idea behind it was for the coding train videos on a neural network but I tried to manipulate it in Java and it didn't work.I search lambda expressions but when I use it it's only let me pass method like Math.cos(arg) with an argument inside. but I want it to pass without any arguments the current function looks like this

interface lambda<T> {
double foo(T fn);
}

public void map(T fn) {
    for(int i = 0 ; i< this.getRow() ; i++) {
        for(int j = 0 ; j< this.getCol(); j++) {
            int a = i;
            int b = j;
            lambda mycode = (T) -> setData(matrix[a][b], fn);
            matrix[i][j] = mycode.foo(fn);
        }
    }
}
private double setData(double data, T fn) {
    data = (double) fn;
    return data;
}

when I send a call from my main class I can only call with arguments like

matrix.map(Math.cos(matrix.getData(0,0))

but it apply on each value in the matrix the cos of data at 0,0

I wish it will look more like this

matrix.map(Math.cos())

or even

Matrix.map(function())

is there a way in java to pass methods as parameters without entering arguments in them?

like image 354
eyal mazuz Avatar asked Feb 03 '18 05:02

eyal mazuz


2 Answers

Java 8 was shipped with enormous number of functional interfaces. You can use one of those to describe the expected function to be passed as parameter in your method.

In your case, for passing a function which excepts a single double parameter and applys a logic, use java.util.function.DoubleUnaryOperator:

static double foo(DoubleUnaryOperator fn){
    double aNumber = 2.0;  
    return fn.applyAsDouble(aNumber);
}

And then create a lambda (or an object which implements DoubleUnaryOperator) and pass it to the foo method:

foo(d -> d * 3);

or

public class Fn implements DoubleUnaryOperator {
    @Override
    public double applyAsDouble(double d) {
        return d * 3;
    }
}
like image 177
Shmulik Klein Avatar answered Oct 17 '22 13:10

Shmulik Klein


Use :: operator, to pass method reference, such as

Math::cos

Also, you need to make sure, method where you are passing method reference, should accept functional interface

That said,

void map(Consumer<T> fn)
like image 26
Ravi Avatar answered Oct 17 '22 12:10

Ravi