Skip to content

Program 11 : Lambda Expressions

Create a Java application utilizing lambda expressions to simplify code and implement block lambda expressions.

java
public class LambdaExpressionsDemo {

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

    public static void main(String[] args) {
        System.out.println("--- Simple & Block Lambda Expressions ---");

        MathOperation addition = (a, b) -> a + b;
        System.out.println("Executing addition (10 + 5): " 
	        + addition.operate(10, 5));
		
        MathOperation subtraction = (int a, int b) -> a - b;
        System.out.println("Executing subtraction (10 - 5): " 
	        + subtraction.operate(10, 5));		
		

        MathOperation multiplication = (a, b) -> { return a * b; };	
        System.out.println("Executing multiplication (10 * 5): " 
	        + multiplication.operate(10, 5));
			
		MathOperation division = (a, b) -> {
            if (b == 0) {
                System.out.println("Error: Cannot divide by zero!");
                return 0;
            }
            return a / b;
        };
        System.out.println("Executing division (10 / 5): " 
	        + division.operate(10, 5));
        
        System.out.println("Executing division by zero (10 / 0): " 
	        + division.operate(10, 0));
    }
}
--- Demonstrating Simple and Block Lambda Expressions ---
Executing addition (10 + 5): 15
Executing subtraction (10 - 5): 5
Executing multiplication (10 * 5): 50
Executing division (10 / 5): 2
Error: Cannot divide by zero!
Executing division by zero (10 / 0): 0

java
public class FactorialLambda {
	// A functional interface with one abstract method
	interface NumericFunction {
	    int calculate(int n);
	}

    public static void main(String[] args) {

        System.out.println("--- Factorial Lambda Expressions ---");
        
        NumericFunction factorial = (n) -> {
            int result = 1;
            for (int i = 1; i <= n; i++) {
                result = i * result;
            }
            return result; // Explicit return statement is needed
        };

        int number = 5;
        System.out.println("The factorial of " 
	        + number + " is " + factorial.calculate(number)); 
	    // Outputs 120

        number = 7;
        System.out.println("The factorial of " 
	        + number + " is " + factorial.calculate(number)); 
		// Outputs 5040
    }
}

java
interface NumericFunc {
	int func(int n);
}

NumericFunc smallestF = (n) -> {
	int result = 1;
	n = Math.abs(n);
	for (int i = 2; i <= n / i; i++) {
		if ((n % i) == 0) {
			result = i;
			break;
		}
	}
	return result;
};

System.out.println("Smallest factor of 12 is " 
			+ smallestF.func(12));
System.out.println("Smallest factor of 11 is " 
			+ smallestF.func(11));
Smallest factor of 12 is 2
Smallest factor of 11 is 1

Program Explanation

  1. Functional Interface (MathOperation):

    • To use a lambda expression, you need a functional interface, which is an interface with exactly one abstract method.
    • We define MathOperation with a single abstract method, operate(int a, int b). The @FunctionalInterface annotation is used to ensure this rule is followed.
  2. Simple Lambda Expressions:

    • These are concise, single-line expressions perfect for simple operations. The syntax (parameters) -> expression is used.
    • addition and subtraction are implemented this way. The compiler automatically infers the parameter types from the MathOperation interface.
  3. Block Lambda Expression:

    • When an operation is more complex and requires multiple lines of code, a block lambda is used.
    • A block lambda is enclosed in curly braces {}, just like a standard method body. If it is expected to return a value, an explicit return statement is required.
    • The division operation uses a block lambda to add a check that prevents division by zero, making the code safer.

Made with ❤️ for students, by a fellow learner.