Lamda Expression
Lamda Expression
• Lambda expressions are similar to methods, but they do not need a name and
they can be implemented right in the body of a method.
Java 8 Lambda Expressions Syntax
• Java Lambda Expression Syntax
Example
(x,y) -> x+y
Structure of lambda expression
• It makes sense to use an access modifier when creating a method that
belongs to a class, but since lambda expressions are not related to a
class, an access modifier is not needed.
• There is no need to specify a method name, as the function provided
by a lambda expression will be used through a variable.
• Since the compiler knows the return type of the written lambda
expression -it is specified by us, I’ll mention-, there is no need to
specify a return type.
• As in the above clause, there is no need to specify the types of
parameters, since the compiler knows the types of parameters.
• If a lambda expression is a single line, the curly braces are optional.
greetingFunction = () -> System.out.println("Hello world!");
doubleNumberFunction = a -> a * 2;
• If the lambda is more than one expression we can use { } and return
(x, y) -> {
int sum = x + y;
int avg = sum / 2;
return avg;
}
Parameter based LE approach
No Parameter Syntax
() -> {
//Body of no parameter lambda
}
One Parameter Syntax
(p1) -> {
//Body of single parameter lambda
}
Two Parameter Syntax
(p1,p2) -> {
//Body of multiple parameter lambda
}
Example
A lambda expression cannot stand alone in Java, it needs to be associated with a
functional interface.
interface MyMath {
int getDoubleOf(int a);
}
For example
Label label = new Label();
Button button = new Button("Send");
button.addActionListener((ActionEvent e) -> label.setText("Sent...")); //Compile Time Error
label = new Label();
The types of a Lambda Expression
The lambda receives a type when it is assigned to a functional interface type in one of the
following ways:
• Direct assignment to a functional type, e.g. myPredicate = s -> s.isEmpty()
• Passing it as a parameter that has a functional type, e.g. stream.filter(s -> s.isEmpty())
• Returning it from a function that returns a functional type, e.g. return s -> s.isEmpty()
• Casting it to a functional type, e.g. (Predicate<String>) s -> s.isEmpty()
Rules for the body of a lambda expression
• The body of the lambda expression can be either a single expression or
more statements.
• If we are using a single expression as the body of a lambda expression,
then no need to enclose the body with curly braces ({}).
• If we are using one or more statements as the body of a lambda
expression, then enclosing them within curly braces({}) can be
mandatory.
• A lambda expression can have zero (represented by empty
parentheses), one or more parameters. The type of the parameters
can be declared explicitly, or it can be inferred from the context. If
there is a single parameter, the type is inferred and is not mandatory to
use parentheses.
Rule cont.,
We can reference the following types of methods:
• Static method
• Instance method on parameter objects
• Instance method
• Constructor
4. return type. 4. No return type – The java 8 compiler is able to infer the
return type by checking the code. you need not to mention it
explicitly.
Lambda Expressions With Description
Lambda Expressions Description
()-> System.out.println(“JFS”); Takes nothing and returns nothing
(int a)->a*a Takes int and returns int
String s1,String s2)->{ Takes two strings and returns nothing
System.out.println(s1);
System.out.println(s2);
}
(double)->d Takes double and retunrs double
()->{} Takes nothing and returns nothing. It
has an empty body.
Advantages of Lambda Expressions
• Enables functional programming.
• Makes the code more readable.
• Allows getting rid of boilerplate codes.
• Facilitates the use of APIs and libraries.
• Supports parallel programming.
Points to remember
• Lambda Expression facilitates functional programming and simplifies
the development a lot.
• It provides a clear and concise way to represent one method interface
using an expression. It is very useful in the collection library. It helps
to iterate, filter, and extract data from the collection.
• The Lambda expression is used to provide the implementation of an
interface that has a functional interface. It saves a lot of code. In the
case of the lambda expression, we don't need to define the method
again for providing the implementation. Here, we just write the
implementation code.
• Java lambda expression is treated as a function, so the compiler does
not create a .class file.
• Any lambda expression is an create object in Java.
How JVM represented to lambda expression?
• For Lambda expressions, the compiler doesn't translate them into
something which is already understood by JVM.
• Lambda syntax that is written by the developer is desugared into
JVM level instructions generated during compilation, which means
the actual responsibility of constructing lambda is deferred to
runtime.
Where To Use Lambda Expressions?
• Lambda expressions are used where an instance of functional interface
is expected.
• Functional interface is an interface which has only one abstract method.
• Functional interfaces can have any number of default methods.
• But, they must have only one abstract method. Comparator, Runnable
AndActionListener are some examples of functional interfaces.