Saturday, 1 June 2019

Java 8 | Lambda expression examples

In this post, we will check various examples to understand the power of Lambda expressions. As Lambda expressions were introduced in Java SE 8, so we need to install java 8 or higher version to compile and run the following examples.

Lambda to check the number is Even

/**
 * This is the functional interface with unimplemented method to check number is
 * even.
 * @author rajesh.dixit
 */
interface Arithmatic {
     boolean isNumberIsEven(int num);
}

/**
 * This is test class to check number is even
 */
public class CheckNumberIsEven {

     public static void main(String[] args) {

          // Lambda expression based implementation to check number is even.
          Arithmatic arithmatic = (num) -> (num % 2 == 0);
          System.out.println(arithmatic.isNumberIsEven(4));
     }
}

Lambda expression for mathematical operations

/**
 * This is the functional interface for mathematical operations.
 * @author rajesh.dixit
 */
interface ArithmaticOper {
     int operation(int num1, int num2);
}

/**
 * This is test class for mathematical operations.
 */
public class ArithmaticOperations {

     public static void main(String[] args) {

          // Lambda expression to add two numbers.
          ArithmaticOper arithmatic = (num1, num2) -> (num1 + num2);
          System.out.println("Addition is: " + arithmatic.operation(4, 5));

          // Lambda expression to subtraction.
          arithmatic = (num1, num2) -> (num1 - num2);
          System.out.println("Subtraction is: " + arithmatic.operation(10, 5));

          // Lambda expression to multiply two numbers.
          arithmatic = (num1, num2) -> (num1 * num2);
          System.out.println("Muliplication is " + arithmatic.operation(10, 5));
     }
}

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...