Java 8 Lambda

With version 8 Java started supporting Lambda expression. With Lambda expressions we can write code in functional programming style by passing functionality as method arguments. Lambda expressions are compact and easy to read. The general syntax for using lambda expressions is (parameters, parameters) -> { statements; }
Java Lambda Properties
  • Optional type declaration : No need to explicitly declare the type of a parameter. The compiler can inference the same from the value of the parameter and the functional interface.
  • Optional parenthesis around parameter : No need to declare a single parameter in parenthesis. For multiple parameters, parentheses are required.
  • Optional curly braces : No need to use curly braces in expression body if the body contains a single statement.
  • Optional return keyword : The compiler automatically returns the value if the body has a single expression to return the value.

Lambda Expression Examples (Styles)

Multiple parameters and multiple lines in body
(parameters) -> { statements; }
(a,b,c) -> { int sum= a+b; return sum*c } 
Single parameter and single Line expression
parameter -> expression
n-> n*n;
no parameter
() -> expression
() -> “success”; 
MyComputeInterface.java
@FunctionalInterface
interface MyComputeInterface {
  public int compute(int... a);
  default boolean isEven(int x) {
    return x / 2 == 0;
  }
}

Following sections shows how to implement and use the above FunctionalInterface using Anonymous Class as well as using Lambda expression.

Implementation with Anonymous Class

UsingAnonymousClass.java
private static void UsingAnonymousClass() {
    MyComputeInterface add = new MyComputeInterface() {
      @Override
      public int compute(int... params) {
        int result = 0;

        for (int n : params) {
          result = result + n;
        }
        return result;
      }
    };

    System.out.println(add.compute(1, 2, 3, 4, 5));
  }
}

Implementation using Lambda Expression

UsingLambda.java
private static void UsingLambda() {
    MyComputeInterface add = (int... params) -> {
      int result = 0;
      for (int n : params) {
        result = result + n;
      }
      return result;
    };

    System.out.println(add.compute(1, 2, 3, 4, 5));
  }

No comments :

Post a Comment

Please leave your message queries or suggetions.