lambda expressions – java version 8

About lambda Expressions:

Lambda Expression been introduced by java 8 , its  a functional programming to make java 8 more faster, clearer coding.
1) A lambda expression Syntax :

parameter -> expression body
or 
(parameters) ->{ statements; }

2.) Lambda Expressions Example:

2.1) First we try traditional approaches :

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
for(Integer n: list) {
System.out.println(n);
}

2.2) Then we try the lambda Expressions:

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
list.forEach(n -> System.out.println(n));

2.3) Math Operations:

//with type declaration
MathOperation addition = (int a, int b) -> a + b;

//with out type declaration
MathOperation subtraction = (a, b) -> a – b;

 

3. characteristics of a lambda expression: 

  • Optional type declaration − No need to declare the type of a parameter. The compiler can inference the same from the value of the parameter.
  • 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. Curly braces are required to indicate that expression returns a value.



 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s