Lambda Expression ( a new extension of Java 8 )

Popular programming languages like C#, C++, Python, JavaScript etc has the lambda expression feature. In java it was missing. But recently in Java 8 this cool feature has been added.

Topics to be covered in this post-

  • Basic syntax of Lambda expression
  • Important things about it
  • Some benefits of using it

Lambda Expression ( a new extension of Java 8 )

 

Download Code

 

Lambda expression is said anonymous function. Basically it is –

  • A method without declaration
  • Shorthand that allows to write a method in the same place it was going to be used.

Syntax

(parameter) -> expression-body
(int x) -> {return x+1;}

This is the syntax of lambda expression. It looks like a method but has no name. Even it has parameter and method body. By the return statement the compiler will understand that this will return an integer. That’s why it is called anonymous function.

 

Important things about lambda expression-

  • For one parameter, parenthesis are optional
  • For multiple parameter, parenthesis are required
  • Declare type of parameters are optional
  • Return statement is optional. If the body has a single value the compiler will automatically return the value.
  • For single statement, curly braces around the expression body are optional.

 

Example

Benefit

  • Fewer codes
  • Implementing collection with lambda expression is very useful
  • Provide implementation of functional interface (an interface which has only one abstract method).

 

 

Download Code

 

 


I hope this post explained basic concepts of lambda expression. If you still have any queries, please do let me know in the comments section below.

Happy Learning 🙂

 

Reference-

https://en.wikipedia.org/wiki/Lambda_expression

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s