_Java_week 13
_Java_week 13
13 Lambda Expressions
Names of Sub-Units
Introduction, Block Lambda Expressions, Generic Functional Interfaces, Passing Lambda Expressions
as Arguments, Exceptions, Variable Capture, Method References, Constructor References, Predefined
Functional Interfaces
Overview
This unit introduces you to the Lambda Expression and explains the Block Lambda expressions. It
explains the generic functional interfaces and describes the Passing Lambda Expression as Arguments.
Also, you will read about the Variable Capture, Method References, Constructor References, etc.
Learning Objectives
Learning Outcomes
https://www.cs.cmu.edu/~charlie/courses/15-214/2014-fall/slides/26-java8.pdf
13.1 INTRODUCTION
Lambda expressions are used to express functional interface instances (a functional interface is one
that has a single abstract method). It's a java.lang file. A good example is Runnable. Lambda expressions
are used to implement a single abstract function, as well as functional interfaces. In Java 8, lambda
expressions were added, and they provide the following features:
1. Allow functionality to be treated as a method argument or code as data.
2. A function that can be created without the need for a class.
3. A lambda expression is an object that may be passed around and executed as needed.
You know that everything is treated as object in Java; therefore, objects are in large numbers therein.
Performing operations on such large number of objects is very difficult. To handle a operation on large
number of objects, Java provides java.util package in which various objects are stored as a single object,
known as Collection Object. You can perform operations on various objects by using the loops, such
as for-each loop. However, this loop will allow you to handle the object separately and not collectively.
Therefore, you need to improve the functional aspect, which can be easily done by using lambda
expressions as these are treated as objects by the JVM.
A lambda expression refers to a method that has no name; no access specifier private, public or
protected; and no value return declaration. This type of method is also known as anonymous method
or closure. Like anonymous class, a lambda expression can be used for performing a task without a
name. It is included in Java SE 8. Through lambda expressions, functionality can be passed as method
arguments and code as data.
Lambda expressions are two different constructs. The first construct is the lambda expression itself;
and the second construct is the functional interface.
2
UNIT 13: Lambda Expressions JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
A functional interface is an interface that consists only a single abstract method, which specifies the
intended purpose of the interface. For example, the Runnable interface is a functional interface and it
contains a method: run(). Therefore, the run() method defines the action of the Runnable interface. A
functional interface also sets the target type of a lambda expression. It means a lambda expression can
be used only in the context in which its target type is specified. Note that a functional interface is called
Single Abstract Method (SAM) type.
Consider the following code snippet for understanding the concept of lambda expression, in which a
simple method is created for showing a message. Let us first declare a simple message as:
public void showMgs()
{
System.out.println("Hello Readers!");
}
Now, convert the preceding method into a lambda expression by removing the public access specifier,
return type declaration, such as void, and the name of method ‘showMsg’. The lambda expression is
shown as follows:
() -> {System.out.println("Hello Readers!"); }
The basic structure of a lambda expression comprises:
Formal parameters separated by commas and enclosed in parentheses.
Arrow operator or called lambda operator, ->
A single expression or a statement block
If a single expression is specified, the Java runtime environment automatically evaluates the expression
and then returns its value. You can also use a return statement, but it should be enclosed in braces as it
is not an expression.
In Java, you can define lambda in two ways: using a single expression and other type consists of a block
of code. For example, consider the following expression:
() -> 560.19
This lambda expression is not having any parameters, thus the parameter list is empty. It returns the
constant value 560.19. It is similar as the functioning of the following method:
double myMeth() { return 560.19; }
Now, consider the following expression with a parameter:
(a) -> (a % 2)==0
This lambda expression returns true if the value of parameter x is even. Note that a lambda expression,
like a named method, can specify as many parameters as required.
3
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming
4
UNIT 13: Lambda Expressions JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
13.6 EXCEPTIONS
An exception in a lambda expression is a feature to test lambda. It is basically an unwanted event
in lambda expression which arises during the implementation of the program. However, a lambda
expression omits a checked exception, which is well-suited with the exception’s and it is listed in the
5
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming
omits division in the functional interface as a nonconcrete method. An unexcepted, even in lambda
occurs during its run time, in which the normal instruction of the program gets disturbed.
The following java program is used to implement the exception for lambda is as follows:
class Main {
public static void main(String[] args) {
try {
// code that generate exception
int divideByZero = 100/ 0;
System.out.println("Rest of code in try block");
}
catch (ArithmeticException e) {
System.out.println("Arithmetic exception => " + e.getMessage());
}
}
}
The output of given java code is follows:
Arithmetic exception => / by zero
6
UNIT 13: Lambda Expressions JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
7
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming
The following java program is used to implement the instance variable capture are as follows:
import java.io.*;
public class Employee {
public String name;
//Salary is display in employee class
private double salary;
public Employee (String empName) {
name = empName;
}
// Salary variable is alloted a value
public void setSalary(double empSalary) {
salary = empSalary;
}
// Implementation of employee details
public void printEmp() {
System.out.println("Name : " + name );
System.out.println("Salary :" + salary);
}
public static void main(String args[]) {
Employee empOne = new Employee("Sanjay Kumar");
empOne.setSalary(25000);
empOne.printEmp();
}
}
The output of given java code is as follows:
Name : Sanjay Kumar
Salary :25000.0
8
UNIT 13: Lambda Expressions JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
There are different types of method references. We will begin with method references to static methods.
9
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming
10
UNIT 13: Lambda Expressions JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
11
JGI JAINDEEMED-TO-BE UNIVERSIT Y
Java Programming
The following java code is used to implement the constructor references are as follows:
// Importing input output classes
import java.io.*;
class GenericConstructor {
// Member variable of this class
private double v;
<T extends Number> GenericConstructor(T t)
{
v = t.doubleValue();
}
void show()
{
System.out.println("v: " + v);
}
}
class GFG {
// Main driver method
public static void main(String[] args)
{
// Displaying the message
System.out.println("Number to conversion twice:");
GenericConstructor object1
= new GenericConstructor(35);
GenericConstructor object2
= new GenericConstructor(206.9F);
object1.show();
object2.show();
}
}
The output of given java code is as follows:
Number to conversion twice:
v: 35.0
v: 206.89999389648438
12
UNIT 13: Lambda Expressions JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
After writing a lambda expression, you can call and execute it like a method. You can call a lambda
expression by creating a functional interface, which is an interface comprising only one abstract
method. However, it may have multiple static or default methods. The advantage of using functional
interface is that it can be used for assigning a lambda expression or as a method reference.
The following java program is used to create lambda expression and assigned to an object of a functional
interface are as follows:
class LambdaExpression
{
//functional interface
interface FuncInterface
{
void showMsg();
}
public static void main(String args[])
{
FuncInterface Fi = () -> { System.out.println("Hello
13
JGI JAINDEEMED-TO-BE UNIVERSIT Y
Java Programming
Dreamtech Press"); };
Fi.showMsg();
}
}
The output of given java code is as follows:
Hello Dreamtech Press
13.12 GLOSSARY
14
UNIT 13: Lambda Expressions JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
https://www.journaldev.com/37273/java-14-features
http://dig.cs.illinois.edu/papers/Mazinanian_OOPSLA_2017.pdf
Discuss with your friends and classmates about the concept of lambda expression in Java. Also,
15
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming
discuss about the block lambda expression, Method reference and Predefined lambda expression
as argument.
LAB EXERCISES
Exercise A: Write a Java program to implement a Lambda Expression with a single parameter. Let the
parameter type be an integer.
Solution: The program is as follows:
public class LambdaExpDemo
{
public static void main(String[] args)
{
I a=(age)->{
return "Your age is: "+age;
};
System.out.println(a.set(25));
}
}
interface I{
public String set(int age);
}
Output:
Your age is: 25
16
UNIT 13: Lambda Expressions JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Explanation:
In this program, we have created an interface named I with a String type method named set() having
an integer parameter age. In the main() method, an instance of the I interface is created with the help of
lambda expression -> having one parameter. Lambda expression will return the age.
Exercise B: Write a Java program to implement a Lambda Expression with multiple Parameters. Let
both the type of parameters be Strings.
Solution: The program is as follows:
public class LambdaExpDemo1
{
public static void main(String[] args)
{
I a=(name, section)->{
return "Welcome, "+name+". You are in "+ section+" class.";
};
System.out.println(a.set("Chirag", "12-C"));
}
}
interface I{
public String set(String name, String section);
}
Output:
Welcome, Chirag. You are in 12-C class.
Explanation:
In this program, we have created an interface named I with a String type method named set() having
two string type parameter name and section. In the main() method, an instance of the I interface is
created with the help of lambda expression -> having two parameters. Lambda expression will return
the name and section.
17