lambda

Java Lambda Expressions

Java Lambda Expressions

Lambda expressions are a way to provide clear and concise syntax for writing anonymous methods (functions) in Java. They enable you to pass functionality as arguments to methods, or store them as variables.

Basic Lambda Expression

interface MathOperation {
    int operate(int a, int b);
}

public class LambdaExample {
    public static void main(String[] args) {
        // Lambda expression for addition
        MathOperation add = (a, b) -> a + b;
        System.out.println("Addition: " + add.operate(5, 3));
    }
}
    

In this example, a lambda expression (a, b) -> a + b is used to implement the operate() method of the MathOperation interface.

Lambda Expression with Multiple Statements

interface MathOperation {
    int operate(int a, int b);
}

public class LambdaExample {
    public static void main(String[] args) {
        // Lambda expression with multiple statements
        MathOperation multiply = (a, b) -> {
            System.out.println("Multiplying " + a + " and " + b);
            return a * b;
        };
        System.out.println("Multiplication: " + multiply.operate(5, 3));
    }
}
    

Lambda expressions can contain multiple statements. In this case, the multiplication result is printed before the final result is returned.