CoreJavaTutorials
Contribute Us | Ask Question |

What is Lamda 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 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
		

Second Example of Lamda expression

import java.util.*;
import java.util.*;
interface Test{
void show(String name); }
class TestLamda
{
public static void main(String args[])
{
Test t=(name)-> {System.out.println("hello"+" "+name);}; //implementation of show method
t.show("shashank");//calling method show of interface
}
}

Output



hello shashank