Saturday, July 25, 2015

Syntax for Lambda expression in Java

In this article, we try to understand the very basic use of Lambda expression with syntax and many examples. If you want to look what is Lambda and the basic idea behind it, I encourage to read this my article on the basic. I will try to cover all the basic use of Lambda expression in the tutorial.


Syntax for Lambda Expressions
A lambda expression describes an anonymous function. The general syntax for using lambda expressions is very similar to declaring a method. The general syntax is
A lambda expression consists of a list of parameters and a body that are separated by an arrow (->).
The list of parameters is declared the same way as the list of parameters for methods. The list of parameters is enclosed in parentheses, as is done for methods.
The body of a lambda expression is a block of code enclosed in braces. Like a method's body, the body of a lambda expression may declare local variables; use statements including break, continue, and return; throw exceptions, etc.

Unlike a method, a lambda expression does not have four parts.

  1. A lambda expression does not have a name
  2. A lambda expression does not have a return type. It is inferred by the compiler from the context of its use and from its body
  3. A lambda expression does not have a throws clause. It is inferred from the context of its use and its body.
  4. A lambda expression cannot declare type parameters. That is, a lambda expression cannot be generic


Basic example to understand Lambda
Lambda expression are invoked via Function Interface.

Function Interface
A functional interface is simply an interface that has exactly one abstract method. The following types of methods in an interface do not count for defining a functional interface:

  • Default methods
  • Static methods
  • Public methods inherited from the Object class

More detail on Function detail.

Runnable is an example of Function interface, (check Runnable Java 8 doc) so we can use Runnable interface in term of Lambda expression.
Runnable interface method does not take any input and does not return anything. So it lambda expression will look like
() -> {  statements;  }


Example
Similarly, Java 8 has many Functional interface for different purpose. Here is the list of commonly used function interface in the package java.util.function


Following table contains some examples of lambda expressions and equivalent methods. I have given a suitable name to methods as you cannot have a method without a name in Java. The compiler infers the return type of lambda expressions.


Example : how to use above lambda expression with function interface.


One of the goals of the lambda expression was to keep its syntax concise and let the compiler infer the details. The following sections discuss the shorthand syntax for declaring lambda expressions.


Omitting Parameter Types
You can omit the declared type of the parameters. The compiler will infer the types of parameters from the context in which the lambda expression is used

// Types of parameters are declared
(int x, int y) -> { return x + y; }

// Types of parameters are omitted
(x, y) -> { return x + y; }

If you omit the types of parameters, you must omit it for all parameters or for none. You cannot omit for some and not for others. The following lambda expression will not compile because it declares the type of one parameter and omits for the other:

// A compile-time error
(int x, y) -> { return x + y; }


Declaring a Single Parameter
Sometimes a lambda expression takes only one parameter. You can omit the parameter type for a single parameter lambda expression as you can do for a lambda expression with multiple parameters. You can also omit the parentheses if you omit the parameter type in a single parameter lambda expression. The following are three ways to declare a lambda expression with a single parameter:

// Declares the parameter type
(String msg) -> { System.out.println(msg); }

// Omits the parameter type
(msg) -> { System.out.println(msg); }

// Omits the parameter type and parentheses
msg -> { System.out.println(msg); }

The parentheses can be omitted only if the single parameter also omits its type. The following lambda expressionwill not compile:

// Omits parentheses, but not the parameter type, which is not allowed.
String msg -> { System.out.println(msg); }



Declaring No Parameters
If a lambda expression does not take any parameters, you need to use empty parentheses.

// Takes no parameters
() -> { System.out.println("Hello"); }

It is not allowed to omit the parentheses when the lambda expression takes no parameter. The following declaration will not compile:

-> { System.out.println("Hello"); }



Parameters with Modifiers
You can use modifiers, such as final, in the parameter declaration for explicit lambda expressions. The following two lambda expressions are valid:

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

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

The following lambda expression will not compile because it uses the final modifier in parameter declarations, but omits the parameter type:
(final x, final y) -> { return x + y; }


Declaring Body of Lambda Expressions
The body of a lambda expression can be a block statement or a single expression. A block statement is enclosed in braces; a single expression is not enclosed in braces
When a block statement is executed the same way as a method’s body. A return statement or the end of the body returns the control to the caller of the lambda expression.

When an expression is used as the body, it is evaluated and returned to the caller. If the expression evaluates to void, nothing is returned to the caller. The following two lambda expressions are the same; one uses a block statement and the other an expression

// Uses a block statement. Takes two int parameters and returns their sum.
(int x, int y) -> { return x + y; }

// Uses an expression. Takes a two int parameters and returns their sum.
(int x, int y) -> x + y

The following two lambda expressions are the same; one uses a block statement as the body and the other an expression that evaluates to void:

// Uses a block statement
(String msg) -> { System.out.println(msg); }

// Uses an expression
(String msg) -> System.out.println(msg)

Check out this link for more examples



If you know anyone who has started learning Java, why not help them out! Just share this post with them.Thanks for studying today!...

9 comments:

  1. Very useful and informative blog. Thank you so much for these kinds of informative blogs.
    who provides seo services, web development services, logo design services, graphic design ,
    digital markeing and all kind of web design, development and digital marketing services.
    best website design services in gurgaon
    web company in delhi
    web desiging company
    web design & development banner
    web design & development company
    web design & development services
    web design agency delhi
    web design agency in delhi
    web design and development services
    web design companies in delhi
    web design company delhi
    web design company in delhi
    web design company in gurgaon
    web design company in noida
    web design company list
    web design company services
    web design company website
    web design delhi
    web design development company
    web design development services
    web design in delhi
    web design service
    web design services company
    web design services in delhi
    web designer company
    web designer delhi
    web designer in delhi
    web designers delhi
    web designers in delhi
    web designing & development
    web designing advertisement
    web designing and development
    web designing and development company
    web designing and development services
    web designing companies in delhi
    web designing company delhi
    web designing company in delhi
    web designing company in gurgaon
    web designing company in new delhi
    web designing company in noida
    web designing company logo
    web designing company sites
    web designing company websites
    web designing delhi
    web designing in delhi
    web designing in gurgaon
    web designing in gurgaon
    web designing service
    web designing services
    web designing services delhi

    ReplyDelete
  2. Thanks for sharing information
    "Pressure Vessel Design Course is one of the courses offered by Sanjary Academy in Hyderabad. We have offer professional
    Engineering Course like Piping Design Course,QA / QC Course,document Controller course,pressure Vessel Design Course,
    Welding Inspector Course, Quality Management Course, #Safety officer course."
    Piping Design Course
    Piping Design Course in India­
    Piping Design Course in Hyderabad
    Welding Inspector Course
    Quality Management Course
    Quality Management Course in india
    Safety officer course

    ReplyDelete
  3. Nice Post
    We are the best piping design course in Hyderabad, India. Sanjary academy Offers Piping Design Course and Best Piping Design Training Institute in Hyderabad. Piping Design Institute in India Piping Design Engineering.
    Piping Design Course
    Piping Design Course in india
    Piping Design Course in hyderabad

    ReplyDelete
  4. Eminem net worth 2021: Eminem is a multi-platinum selling American rapper, producer and actor who has a net worth of $230 million. He is consistently one of the highest-paid entertainers in the world.

    ReplyDelete
  5. Thanks for sharing this information with us and it was a nice blog.Envizon Studio is a leading Best web design company in Hyderabad offering all kinds of custom built websites, web portals & web applications. Please visit our website for more Information.

    ReplyDelete