Illuminatiiiiii
11/11/2018 - 6:55 AM

Using Lambdas as Parameters

For Episode 64 of the Java Series: https://youtu.be/47QO3BAyh9o

interface NumbersAreCool{
    int numberMethod(int num);
}
public class Main {

    //A Method that uses a lambda as a parameter. We use a second parameter to specify what the parameter of the expression will be
    static int randomMethod(NumbersAreCool a, int b){
        return a.numberMethod(b);
    }

    //We can provide a second method if we want, using the same functional interface as a parameter.

    public static void main(String[] args) {

        int num1; //The variable we will use to store the return value of our method
        //We call upon our method, and provide a block lambda expression as the first parameter.
        //The expression basically defines an implementation of our functional interface
        // that takes a single integer, and multiples it by 5, then returns the result.
        //Then we provide a second parameter to the method, which will be our variable
        //entered into the lambda expression.
        num1 = randomMethod((int a) -> {
            int temp = 5;
            return a * temp;
        }, 5);
        System.out.println(num1);
        //If you think about it, in this case, we both define and use a lambda expression at the same time. Pretty cool.

        //Lets use the method a second time and make a second lambda expression
        int num2;
        num2 = randomMethod((int a) -> { //Another factorial finding lambda expression. I'm not very creative.
            int result = 1;
            for (int i = 1; i <= a;i++){
                result = i * result;
            }
            return result;
        }, 7);
        System.out.println(num2);

        //We can even define the lambda expression and plug it in later
        NumbersAreCool squareRoot = (int a) -> (int) Math.sqrt(a); //Finds the square root of a number, returns that result.

        //Lets use our special method here and plug in the lambda expression
        int num3;
        num3 = randomMethod(squareRoot, 25); //Much easier to read
        System.out.println(num3);
    }
}