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!...

8 comments:

  1. I will always let you and your words become part of my day because you never know how much you make my day happier and more complete. There are even times when I feel so down but I will feel better right after checking your blogs. You have made me feel so good about myself all the time and please know that I do appreciate everything that you do my assignment for me have

    ReplyDelete
  2. Do you have a question about the subject? Please post your question in the comments box below, and one of our experts will respond professional celebrity ghostwriting services. Visit our website for a Java training curriculum:

    ReplyDelete
  3. Do you have any problem about your class or exam so please feel Safe to contact us.
    Looking for Pay Someone To Take My Online Class? Yes, we’re the most trusted best online class help provider. We are pioneer of do my online class for me.

    ReplyDelete
  4. Assuming that you are keen on information designing independent, there are numerous stages that offer the chance to track down a reasonable competitor. Here are the top picks to search for specialists. As perhaps of the biggest independent data set on the planet, Upwork is perfect as far as the ability pool. Here you can post a task offering and hold on until competitors apply. From that point onward, an organization can choose a reasonable supplier. One of the benefits is that each specialist has a history of past tasks and evaluations. There is likewise an installment security highlight, which adds to the wellbeing of collaboration>> data analyst freelance

    ReplyDelete
  5. Attract Group's dedicated development team service https://attractgroup.com/services/hire-dedicated-development-team/ stands out for its efficiency and commitment to delivering high-quality results. Their team of skilled professionals is adept at handling a wide range of projects, ensuring that clients receive tailor-made solutions that meet their specific needs. With a focus on clear communication, timeliness, and expertise, Attract Group provides a reliable option for businesses looking to scale their development efforts effectively. Overall, their dedication to excellence makes them a top choice for those seeking top-tier development services.

    ReplyDelete