What Is Lambda Expression ?

What Is Lambda Expression ?

Lambdas are the one of the most important new addition in java 8.They are use to implement functional programming and functional interface.
Most major programming languages already have support for lambda expressions , java is late to introduce lamda expression but introduce with effectiveness
The biggest problem to introduce lambdas without requiring recompilation of existing binaries

A Java 8 lambda is basically a method in Java without a declaration usually written as

(parameters) -> { body }

For example:

(int x, int y) -> { return x + y; }

x -> x * x

( ) -> x

Syntax Of Lambda Expression

It can have zero or more parameters separated by commas and their type can be explicitly declared or inferred from the context. Parenthesis are not needed around a single parameter.

Parenthesis ( ) is used to denote zero parameters.

The body can contain zero or more statements.

Braces are not needed around a single-statement body.

Advantages Of Lamda Expression

  1. Writing leaner more compact code
  2. Enabling functional programming
  3. Helpful in parallel programming
  4. Helpful in developing more generic, flexible and reusable APIs
  5. Enable to pass behaviors as well as data to functions

Example 1 : Lambda Expression

import java.util.*;
public class LambdaExample {
  public static void main(String args[]) {
    List values = Arrays.asList(1, 2, 3, 4, 5);
    values.forEach(x -> {
      System.out.println(x);
    });
  }
}

Output

1
2
3
4
5

Example 2 : Lambda Expression

import java.util.*;
interface Test {
  void show(String name);
}
class LambdaExample {
  public static void main(String args[]) {
    Test t = (name) -> {
      System.out.println("Hi" + " " + name);
    };
    t.show("Tutorial");
  }
}

Output

Hi Tutorial