[go: up one dir, main page]

0% found this document useful (0 votes)
24 views22 pages

Lamda Expression

Lambda expressions allow implementing functional interfaces with anonymous methods. They make code more concise and readable. Lambda expressions are useful for filtering, mapping and reducing collections and support functional programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views22 pages

Lamda Expression

Lambda expressions allow implementing functional interfaces with anonymous methods. They make code more concise and readable. Lambda expressions are useful for filtering, mapping and reducing collections and support functional programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Lambda Expressions

Why Lambda expressions ?


• Lambda expressions are a new and important feature included in Java
SE 8.
• They provide a clear and concise way to represent one method
interface using an expression.
• Lambda expressions also improve the Collection libraries making it
easier to iterate through, filter, and extract data from a Collection.
• To provide the implementation of Functional interface.
• Less coding.
Benefits of lambda expressions in Java
• Conciseness.
• Reduction in code bloat.
• Readability.
• Elimination of shadow variables.
• Encouragement of functional programming.
• Code reuse.
• Enhanced iterative syntax.
• Simplified variable scope.
• Lambda expressions removes verbosity and repetition of code.
What is Lambda Expression?
• A lambda expression is a short block of code which takes in parameters and
returns a value.
• Java 8 Lambda Expressions can be defined as methods without names i.e
anonymous functions.
• Like methods, they can have parameters, a body, a return type and possible list
of exceptions that can be thrown.
• But unlike methods, neither they have names nor they are associated with any
particular class.

• 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

(argument-list) -> {body}


Java lambda expression consists of three components.
• Argument-list: It can be empty or non-empty as well.
• Arrow-token: It is used to link arguments-list and body of expression.
• Body: It contains expressions and statements for the lambda expression.

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;

addNumberFunction = (a, b) -> {


return a + b;
}
safeDivideFunction = (a, b) -> {
if (b == 0) return 0;
return a / b;
}
Example
(int a) -> a * 2; // Calculate the double of a
a -> a * 2; // or simply without type

(a, b) -> a + b; // Sum of 2 parameters

• 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);
}

MyMath d = a -> a * 2; // associated to the interface


d.getDoubleOf(4); // is 8
Lambdas as Objects
A Java lambda expression is essentially an object. You can assign a lambda
expression to a variable and pass it around, like you do with any other object. Here
is an example:

public interface MyComparator {


public boolean compare(int a1, int a2);
}
MyComparator myComparator = (a1, a2) -> a1 > a2;
boolean result = myComparator.compare(2, 5);
Use Of Local Variables Inside Lambda Expression
You can use local variables inside a lambda expression just like anonymous inner classes
provided they must be final or effectively final.

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

Java lambdas can capture the following types of variables:


• Local variables
• Instance variables
• Static variables
Lambda expression vs method in Java
A method (or function) in Java A lambda expression in Java has these main parts:
has these main parts: (Lambda expression only has body and parameter list)

1. Name 1. No name – function is anonymous so we don’t care about


the name

2. Parameter list 2. Parameter list

3. Body 3. Body – This is the main part of the function.

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.

You might also like