CoreJavaTutorials
Contribute Us | Ask Question |

What is Lamda Expression ?

Lambdas are the most important new addition
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

Rules of Lamda 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.

Parenthisis ( ) 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 Hepful 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 Lamda expression

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

Output



1 2 3