Search code examples
lambdajava-8functional-interface

how to pass lambda expression with arguments as parameters in Java 8?


Here is what I tried. and it does not even compile.

public class LambdaExample {

    public static Integer handleOperation(Integer x, Integer y,  Function converter){
                return converter.apply(x,y);
    }

    public static void main(String[] args){
         handleOperation(10,10, Operation::add);
    }

}

class Operation {

    public int add(Integer x, Integer y){
        return x+y;
    }

}

Couple of things I am trying to acheive/learn here is:

1) how to pass lambda expression as method parameter ( in main method above)

2) how to pass parameters to the function (in handleOpertion method, there is compilation error that apply takes only one parameter)


Solution

  • Your handleOperation method takes an object that implements Function, Operation::add (a method reference) doesn't qualify. Also, for two arguments, you'll need to use BiFunction instead.

    Here's an example that should work:

    public class LambdaExample {
    
        public static Integer handleOperation(Integer x, Integer y,  BiFunction<Integer, Integer, Integer> converter){
                    return converter.apply(x,y);
        }
    
        public static void main(String[] args){
             handleOperation( 10,10, new Operation() ); // should return 20
        }
    
    }
    
    class Operation implements BiFunction<Integer, Integer, Integer> {
    
        public Integer apply(Integer x, Integer y){
            return x+y;
        }
    
    }
    

    Updated:

    public class LambdaExample {
    
        public static Integer handleOperation(Integer x, Integer y,  BiFunction<Integer, Integer, Integer> converter){
                    return converter.apply(x,y);
        }
    
        public static void main(String[] args){
             handleOperation( 10,10, Operation::add ); // should return 20
        }
    
    }
    
    class Operation {
    
        public static int add(Integer x, Integer y){
            return x+y;
        }
    
    }