Advance Java: Developed By:-Prof Abhay More
Advance Java: Developed By:-Prof Abhay More
Advance Java
Lecture 3
Page 1|9
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab,
Mumbai, Maharashtra 400604
Developed by:- Prof Abhay More
Module 1
----------------------------------------------------------------------------------------------------------------
Lambda Expressions - Lambda Type Inference, Lambda Parameters,
Lambda Function Body, Returning a Value, From a Lambda Expression,
Lambdas as Objects.
---------------------------------------------------------------------------------------------------------------
Lambda Expressions
Lambda expression is a new and important feature of Java which was included
in Java SE 8. It provides a clear and concise way to represent one method
interface using an expression. It is very useful in collection library. It helps to
iterate, filter and extract data from collection.
The Lambda expression is used to provide the implementation of an interface
which has functional interface. It saves a lot of code. In case of 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 compiler does not create
.class file.
Lambda Expression Syntax
1. (argument-list) -> {body}
Page 2|9
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab,
Mumbai, Maharashtra 400604
Developed by:- Prof Abhay More
Two Parameter Syntax
1. (p1,p2) -> {
2. //Body of multiple parameter lambda
3. }
Type Inference means that the data type of any expression (e.g. method return type or
parameter type) can be detected automatically by the compiler. Java 8 Lambda
expressions also support Type inference. Let’s understand how it works with a few examples.
Suppose we have to calculate the sum of two numbers. As you know, we need an interface
method that consumes two parameters of say Number type and returns the output of the same
type. Let’s create an interface and provide its inline implementation using Lambda
expressions.
interface BiFunction<K,V,R>{
R apply(K k ,V v);
}
Observe that we have declared an interface called BiFunction which has a method, ‘apply’
accepting two parameters of any type K & V respectively and returns another type of value
i.e. R. These types could be same or different as you provide their types during declaration.
1. If you haven’t specified generic types during reference variable declaration, type of
number1 and number2 would be detected as Object class instances.
2. If specified the generic types, it will automatically detected the type and operation
available for that type could be used.
Page 3|9
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab,
Mumbai, Maharashtra 400604
Developed by:- Prof Abhay More
Output:
New thread created
Page 4|9
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab,
Mumbai, Maharashtra 400604
Developed by:- Prof Abhay More
Java 8 onwards, we can assign lambda expression to its functional interface object like this
// Java program to demonstrate Implementation of
// functional interface using lambda expressions
class Test
{
public static void main(String args[])
{
Lambda Parameters
Parameters are the same as function parameters, those are values passed to a
lambda function for it to do something with.
Parameters are usually enclosed in brackets and separated by commas, although
in the case of a lambda, which receives only one parameter, the brackets can be
omitted.
A lambda function can take any number of parameters, including zero, so you
could have something like this:
() -> System.out.println("Hello World!")
This lambda function, when matched to a corresponding interface, will work the
same as the following function:
static void printing(){
System.out.println("Hello World!");
}
Similarly, we can have lambda functions with one, two, or more parameters.
Page 5|9
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab,
Mumbai, Maharashtra 400604
Developed by:- Prof Abhay More
A classic example of a function with one parameter is working on each element
of a collection in a forEach loop:
public class Main {
public static void main(String[] args) {
LinkedList<Integer> childrenAges = new LinkedList<Integer>(Arrays.asList(2, 4, 5, 7));
childrenAges.forEach( age -> System.out.println("One of the children is " + age + " years old."));
}
}
Here, the sole parameter is age. Note that we removed parentheses around it
here, because that's allowed when we have only one parameter.
Using more parameters works similarly, they're just separated by a comma and
enclosed in parentheses. We've already seen two-parameter lambda when we
matched it to Comparator to sort Strings.
Lambda Function Body
A body of a lambda expression consists of a single expression or a statement
block.
If you specify only a single expression as the body of a lambda function
(whether in a statement block or by itself), the lambda will automatically return
the evaluation of that expression.
If you have multiple lines in your statement block, or if you just want to (it's a
free country), you can explicitly use a return statement from within a statement
block:
// just the expression
(s1,s2) -> s1.length() - s2.length()
// statement block
(s1,s2) -> { s1.length() - s2.length(); }
// using return
(s1,s2) -> {
s1.length() - s2.length();
return; // because forEach expects void return
}
Page 6|9
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab,
Mumbai, Maharashtra 400604
Developed by:- Prof Abhay More
Types of Lambda Body
In Java, the lambda body is of two types.
1. A body with a single expression
() -> System.out.println("Lambdas are great");
This type of lambda body is known as the expression body.
2. A body that consists of a block of code.
() -> {
double pi = 3.1415;
return pi;
};
This type of the lambda body is known as a block body. The block body allows
the lambda body to include multiple statements. These statements are enclosed
inside the braces and you have to add a semi-colon after the braces.
In case all your lambda expression is doing is to calculate a return value and
return it, you can specify the return value in a shorter way. Instead of this:
(a1, a2) -> { return a1 > a2; }
Page 7|9
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab,
Mumbai, Maharashtra 400604
Developed by:- Prof Abhay More
The compiler then figures out that the expression a1 > a2 is the return value of
the lambda expression (hence the name lambda expressions - as expressions
return a value of some kind).
Lambdas as Objects
Yes, any lambda expression is an object in Java. It is an instance of a functional
interface. We have assigned a lambda expression to any variable and pass it like
any other object.
Syntax
(parameters) -> expression
or
(parameters) -> { statements; }
In the below example, how a lambda expression has assigned to a variable and
how it can be invoked.
Example
@FunctionalInterface
interface ComparatorTask {
public boolean compare(int t1, int t2);
}
public class LambdaObjectTest {
public static void main(String[] args) {
ComparatorTask ctask = (int t1, int t2) -> {return t1 > t2;}; // lambda expression
boolean b = ctask.compare(10, 3);
System.out.println("The result is: " + b);
}
}
Output
The result is: true
Page 8|9
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab,
Mumbai, Maharashtra 400604
Developed by:- Prof Abhay More
Assignment Questions:
1. Write a Java program using Lambda Expression to print”Hello World”.
2. Write a Java program using Lambda Expression with single parameters.
3. Write a Java program using Lambda Expression with multiple parameters to
add two numbers.
4. Write a Java program using Lambda Expression to calculate the following:
a. Convert Fahrenheit to Celsius
b. Convert Kilometers to Miles.
5. Write a Java program using Lambda Expression with or without return
keyword.
6. Write a Java program using Lambda Expression to concatenate two strings.
Page 9|9