Lambda
Notation
Lambda Notation
Learning Objective
What is Lamda Notation?
Lambda Syntax
Lambda Expression
Lambda Notation
Lambdas are expressed as a single method classes
that represent behavior.
They can either be assigned to a variable or passed
around to other methods just like we pass data as
arguments.
Lambda expressions in Java is written using
syntax (argument) -> (body).
Example : (int a, int b) -> { return a + b; }
Java compiler compiles lambda expressions and
convert them into private method of the class.
Lambda Notation
// Concatenating strings
(String s1, String s2) -> s1+s2;
// Squaring up two integers
(i1, i2) -> i1*i2;
// Summing up the trades quantity
(Trade t1, Trade t2) -> {
t1.setQuantity(t1.getQuantity() + t2.getQuantity());
return t1;
};
Lambda Syntax
A lambda expression has input arguments, a body, and an
optional return value.
input arguments -> body
Each lambda expression has two parts separated by an
arrow token:
The left hand side is method arguments
The right hand side is applying business logic.
The body can either be an expression or block of code,
returning a result or void.
Lambda Expression
Consider the following lambda expression.
(String s1, String s2) → s1+s2, the left hand side of
the arrow (→) token is method argument list.
The arguments to the method are supplied as two
strings.
The right hand side part, contains the logic that
shall be applied in the method.
Lambda Expression
Functional Interface
An interface with exactly one abstract method is called
Functional Interface.
The major benefit of functional interface is that it can
be used with lambda expressions .
Java has defined a lot of functional interfaces in
java.util.function package.
Runnable, Comparator,Cloneable are some of the
examples for Functional Interface.
Example of functional interface
example
For example:
Thread t =new Thread(new Runnable(){
public void run()
{ System.out.println("Runnable implemented by using
Lambda Expression"); }
});
As Runnable is having Single Abstract Method, this as
a Functional Interface and we can use Lambda
expression like below.
Thread t = new Thread(()->{
System.out.println("Runnable implemented by using
Lambda Expression");
});
Lambda Expression
Commonly used Functional Interfaces in Stream API
methods
Function and BiFunction : Function represents a
function that takes one type of argument and returns
another type of argument. Function is the generic form
where T is the type of the input to the function and R is
the type of the result of the function.
Predicate and BiPredicate : It represents a predicate
against which elements of the stream are tested. This is
used to filter elements from the stream.
Consumer and BiConsumer : It represents an
operation that accepts a single input argument and
returns no result.
Interview Questions
What is the use of Lambda Expression ?
What are the characteristics of a Java Lambda
expression?
How will you sort a list of string using Java Lambda
expression?
Any Questions