0% found this document useful (0 votes)
3 views

_Java_week 13

This document provides an overview of Lambda Expressions in Java, covering their fundamentals, block expressions, functional interfaces, and various applications such as passing them as arguments and handling exceptions. It outlines learning objectives and outcomes, explaining concepts like variable capture and method references. The document includes code examples to illustrate the use of lambda expressions and their integration with functional interfaces.

Uploaded by

shitalshalini88
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)
3 views

_Java_week 13

This document provides an overview of Lambda Expressions in Java, covering their fundamentals, block expressions, functional interfaces, and various applications such as passing them as arguments and handling exceptions. It outlines learning objectives and outcomes, explaining concepts like variable capture and method references. The document includes code examples to illustrate the use of lambda expressions and their integration with functional interfaces.

Uploaded by

shitalshalini88
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/ 17

UNIT

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

In this unit, you will learn to:


 Use block lambda expressions and as generic functional interfaces
 Pass Lambda Expressions as arguments
 Handle the exceptions
 Explore variable capture
 Explain lambda expressions as method references and constructor references
 Use functional interfaces
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming

Learning Outcomes

At the end of this Unit, you would:


 Explain the fundamentals of lambda expressions
 Create programs using block lambda expressions
 Explain variable capture using lambda expressions
 Generate programs using lambda expressions as method and constructor references
 Describe creation of programs using functional interfaces

Pre-Unit Preparatory Material

 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.

13.2 LAMBDA EXPRESSION FUNDAMENTALS


A lambda expression is an anonymous or called unnamed method. This method cannot be executed
on its own and used to implement a method defined by a functional interface. In this way, a lambda
expression works, like an anonymous class. Lambda expressions are also commonly called as closures.

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.

13.2.1 Functional Interfaces


As stated, a functional interface is an interface that declares only one abstract method. Prior to JDK
8, all interface methods are implicitly abstract methods. However, from JDK 8 the situation has been
changed. Now, it is possible to specify the default behaviour of a method declared in an interface. This
is called a default method. Now, an interface method is abstract only if it does not specify a default
implementation.

3
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming

The following code snippet shows an example of a functional interface:


interface MyNumber { double getValue();}
In the preceding code snippet, MyNumber is a functional interface, and its function is defined by
getValue(). The getValue() method is implicitly abstract, and it is the only method defined by the
MyNumber interface.

13.3 BLOCK LAMBDA EXPRESSIONS


A lambda block means lambda expression with multiple statements. The multiple statements containing
code are called expression bodies. A lambda expression with expressive bodies is called expression
lambdas. When we use expression lambdas, we have to use a return statement explicitly to return a
value. The following java program is showing an example of expression lambdas are as follows:
interface MaxNumber {
int numFinder(int number1, int number2);
}
public class LambdaMaxNumber {
public static void main(String args[]) {
MaxNumber mn = (number1, number2) -> {
int temp = 0;
if(number1 > number2) {
temp = number1;
} else {
temp = number2;
}
return temp; // explicitly return a value
};
System.out.println("The greater number is : " + mn.numFinder(50, 55));
}
}
The output of given java code is as follows:
D:\Java folder\java LambdaMaxNumber
The greater number is : 55

13.4 GENERIC FUNCTIONAL INTERFACES


A generic functional interface is determined as when a lambda expression is unable to define the type
of parameters. A lambda expression or functional interfaces are connected to each other. A lambda
function cannot be produced a type parameter by its owner, in this case lambda is considered as a
generic. When the target type of lambda expression is defined to be functional interfaces, then the type
parameter or argument is given.
The following java program is used to implement the generic functional interface of a lambda expression
are as follows:
// Generalized functional interface of lambda expression
interface IValue<T> {
T GetValue();
}
public class TrainLambda02 {

4
UNIT 13: Lambda Expressions JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

public static void main(String[] args) {


IValue<Float> reflectIValue;
//Set a lamba expression to a float datatype
reflectIValue = () -> 4.1563f; // Value of float datatype
// Apply method GetValue(), which returns the value of float datatype
float V= reflectIValue.GetValue();
System.out.println("V = " + V);
}
}
The output of given java code is as follows:
java -cp /tmp/jgi85DkVfx TrainLambda02
V = 4.1563

13.5 PASSING LAMBDA EXPRESSIONS AS ARGUMENTS


In terms of passing lambda expression as arguments, a lambda expression is generally used when the
datatype provides a target in the context when the lambda expression passed as an argument. Basically,
the term ‘lambdas’ is commonly used when a lambda expression is passed as an argument. This term
is considered to be a very superior method because it provides a way to pass any feasible code as an
argument. The parameter which is used to pass a lambda expression as an argument should have a
functional interface datatype which is well-suited to the lambda expression.
The following java program is used to implement the lambda expression are as follows:
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<String> Subjects= new ArrayList<>();
// Create an arraylist, adding elememts to it
Subjects.add("Software engineering");
Subjects.add("Operating system");
Subjects.add("Database Management System");
System.out.println("ArrayList: " + Subjects);
// pass lambda expression as parameter to replaceAll() method
Subjects.replaceAll(e -> e.toUpperCase());
System.out.println("Updated ArrayList: " + Subjects);
}
}
The output of given java code is as follows:
ArrayList: [Software engineering, Operating system, Database Management
System]
Updated ArrayList: [SOFTWARE ENGINEERING, OPERATING SYSTEM, DATABASE
MANAGEMENT SYSTEM]

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

13.7 VARIABLE CAPTURE


Variables are generally defined as a name to the memory locations that keeps a value of a specific
datatype. These variables are available within the lambda expression. The term variable capture in
lambda expression can only relate with the variables outside its body. A lambda expression can only
acquire or the group of values of a static variable. The term variable capture in lambda expression is
considered as a distinct condition or state. We may only use a local variable in a lambda expression that
are effectively final. When a variable assigned a specific value and it not get changed from beginning till
the end is considered as effective final variable. Hence, it is not required to assert such variable as final
even though doing so is considered as an error. However, a local variable in lambda expression cannot
be changed.
The following java program illustrates the difference between effectively final and mutable local
variables are as follows:
// Importing input output classes
import java.io.*;
// Interface of the class
interface MyInterface {
void myFunction();
}
// Main class
class GFG {
//initialization
int data = 280;
public static void main(String[] args)
{
GFG gfg = new GFG();
MyInterface intFace = () ->
{

6
UNIT 13: Lambda Expressions JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

System.out.println("Data : " + gfg.data);


gfg.data += 100;

System.out.println("Data : " + gfg.data);


};
intFace.myFunction();
gfg.data += 209;
System.out.println("Data : " + gfg.data);
}
}
The output of given java code is as follows:
Data : 280
Data : 380
Data : 589
It is very important to highlight that we can modify or changed the instance variable from its arising
class. That variable considered as effectively final because it can use a local variable of its enclosure
possibility. In java lambda expression can capture the three types of variables are as follows:
 Local variables
 Instance variables
 Static variables

13.7.1 Local Variable Capture


A local variable in lambda expression refers as the method inside the body. We can only use this type of
variable in lambda expression only within the method. These variables are only executed at the stack
level.
The following java program is used to implement the local variable capture are as follows:
public class Test {
public void PankajAge() {
int Age = 0;
Age = Age + 12;
System.out.println("Age of Pankaj is: " + Age);
}
public static void main(String args[]) {
Test test = new Test();
test.PankajAge();
}
}
The output of given java code is as follows:
Age of Pankaj is: 12

13.7.2 Instance Variable Capture


An instance variable is those variables in lambda expression that are acknowledged in an enclosing class,
but outside the method. These variables are created with the use of “new” keyword. Instance variables
are referred as an instance, because its value is specific and not shareable among other instances.

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

13.7.3 Static Variable Capture


A static variable is also known as class variables in a lambda expression. These variables are created
when the program is started and can be demolished when the program stops. A solitary copy of static
variable is produced and circulates in all the instances of the class. The following java program is used
to implement the static variable capture are as follows:
import java.io.*;
public class Employee {
private static double Salary;
// DEPARTMENT is a constant
public static final String DEPARTMENT = "Computer Science and
Engineering ";
public static void main(String args[]) {
Salary = 40000;
System.out.println(DEPARTMENT + "average Salary:" + Salary);
}
}
The output of given java code is as follows:
Computer Science and Engineering average Salary: 40000.0

8
UNIT 13: Lambda Expressions JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

13.8 METHOD REFERENCES


As discussed earlier, you can use lambda expressions for creating anonymous methods. Sometimes, a
lambda expression is used only for calling an existing method by using its name but not for performing
operations. Lambda expressions use method references that are compact and easy-to-read for calling
existing methods by their names. There are mainly four different types of method references, as shown
in Table 1:

Table 1: Different Types of Method References

Types of References Example


Referencing a static method ContainingClass::staticMethodName
Referencing an instance method of a particular object containingObject::instanceMethodName
Referencing an instance method of an arbitrary object ContainingType::methodName
of a particular type
Referencing to a constructor ClassName::new

There are different types of method references. We will begin with method references to static methods.

13.8.1 Method References to Static Methods


A static method reference is used as lambda expression, which can be well-defined in a class or an
interface. The following java program is used to implement the method references by static methods
are as follows:
import java.util.ArrayList;
import java.util.List;
public class StaticMethodReferenceEx {
public static void main(String a[]) {
List<String> SubjectList = new ArrayList<>();
SubjectList.add("English");
SubjectList.add("Hindi");
SubjectList.add("Maths");
SubjectList.add("Science");
// Print the list element in the normal way
System.out.println("<--- Prior to java-6 --->");
for(String str:SubjectList) {
StaticMethodReferenceEx.printString(str);
}
System.out.println("\n<--- java-6 method reference way --->");
SubjectList.forEach(StaticMethodReferenceEx::printString);
// In the way of lambda expression
System.out.println("\n<--- java-6 lambda expression way --->");
SubjectList.forEach(str -> StaticMethodReferenceEx.
printString(str));
}
public static void printString(String str) {
System.out.println(str);
}
}

9
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming

The output of given java code is as follows:


<--- Prior to java-6 --->
English
Hindi
Maths
Science
<--- java-6 method reference way --->
English
Hindi
Maths
Science
<--- java-6 lambda expression way --->
English
Hindi
Maths
Science

13.8.2 Method References to Instance Methods


Instance method reference, falls under the category of a method reference in which it needs an object
to be produced within a class previously. The following java program is used to implement the instance
method references are as follows:
import java.io.*;
class Foo {
String name = "";
public void Geek(String name) { this.name = name; }
}
class GFG {
public static void main(String[] args)
{
// Manufacturing of instance class
Foo ob = new Foo();
// calling an instance method in the class 'Foo'.
ob.Geek("Hello! Welcome to the world");
System.out.println(ob.name);
}
}
The output of given java code is as follows:
Hello! Welcome to the world

13.8.3 Method References with Generics


A generic method references is a method which means parameterised, such as integer, string, etc. This
method makes us conceivable to generate different classes that work with other datatypes.
The following java program is used to implement the method references with generics are as follows:
public class GenericMethodTest {
// generic method printArray

10
UNIT 13: Lambda Expressions JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

public static < E > void printArray( E[] inputArray ) {


// Display the elements of array
for(E element : inputArray) {
System.out.printf("%s ", element);
}
System.out.println();
}
public static void main(String args[]) {
// Create arrays of Integer, Double and Character
Integer[] intArray = { 5,6,7,8,9,10,11};
Double[] doubleArray = { 2.2, 5.5, 6.7,8.3, 4.3};
Character[] charArray = { 'G','O', 'O','D' };

System.out.println("Array integerArray contains:");


printArray(intArray);

System.out.println("\nArray doubleArray contains:");


printArray(doubleArray); // pass a Double array

System.out.println("\nArray characterArray contains:");


printArray(charArray); // pass a Character array
}
}
The output of given java code is as follows:
Array integerArray contains:
5 6 7 8 9 1011
Array doubleArray contains:
2.25.5 6.7 8.34.3
Array characterArray contains:
GO O D

13.9 CONSTRUCTOR REFERENCES


Similar to the way that you can create references to methods, you can create references to constructors.
Here is the general form of the syntax that you will use:
Class name: new
This reference can be assigned to any functional interface reference that defines a method compatible
with the constructor. The following java program is used to implement the constructor references are
as follows:
class Main {
private String name;
// constructor
Main() {
System.out.println("HEELO!");
name = ", welcome to this world";
}
public static void main(String[] args) {

11
JGI JAINDEEMED-TO-BE UNIVERSIT Y
Java Programming

Main object = new Main();


System.out.println("Good morning" + object.name);
}
}
The output of given java code is as follows:
HEELO!
Good morning, welcome to this world

13.9.1 Constructor References with Generic


Constructor references to generic classes are created in the same fashion. The only difference is that
the type argument can be specified. This works the same as it does for using a generic class to create a
method reference.

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

13.10 PREDEFINED FUNCTIONAL INTERFACES


A functional interface is an interface in which there is exactly one abstract method. Some examples of
functional interface are java.util.comparator, java.lang.Runnable, java.awt.event.ActionListener, java.
util.concurrent.Callable, java.security.PriviligedAction, etc. are some examples of functional interface.
In Java 8, various functional interfaces are introduced that can be extensively used in lambdas
expressions. Table 2, gives the list of functional interfaces in java.util.function packages:

Table 2: List of Functional Interface in java.util.Function

Functional Interface Description


BiConsumer<T,U> It represents an operation which accepts two input arguments, but returns
no result
BiFunction<T,U,R> It represents a function which accepts two arguments and produces a result
BinaryOperator<T> It represents an operation upon two operands of the same type, producing a
result of the same type as the operands
BiPredicate<T,U> It represents a predicate (i.e., Boolean-valued function) of two arguments
BooleanSupplier It represents a supplier of Boolean-valued results
Consumer <T> It represents an operation which accepts a single input argument but
returns no result
DoubleBinaryOperator It represents an operation upon two double-valued operands and producing
a double-valued result
DoubleConsumer It represents an operation that accepts a single double-valued argument
but returns no result
DoubleFunction<R> It represents a function that accepts a double-valued argument and
produces a result
Function<T,R> It represents a function that accepts one argument and produces a result
IntFunction<R> It represents a function that accepts an int-valued argument and produces
a result
LongFunction<R> It represents a function that accepts a long-valued argument and produces
a result

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

Conclusion 13.11 CONCLUSION

 A lambda expression refers to a method that has no name; no access specifier.


 Anonymous class, a lambda expression can be used for performing a task without a name.
 A functional interface is an interface that consists only a single abstract method.
 A lambda block means lambda expression with multiple statements.
 A generic functional interface is determined as when a lambda expression is unable to define the
type of parameters.
 Passing lambda expression as arguments, a lambda expression is generally used when the datatype
provides a target.
 An exception in a lambda expression is a feature to test lambda.
 Variables are generally defined as a name to the memory locations that keeps a value of a specific
datatype.
 Lambda expressions use method references that are compact and easy-to-read for calling existing
methods.
 The constructor reference can be assigned to any functional interface.
 A functional interface is an interface in which there is exactly one abstract method.

13.12 GLOSSARY

 Lambda expression: It refers to a method that has no name; no access specifier.


 Anonymous class: It is a lambda expression can be used for performing a task without a name.
 Functional interface: It is an interface that consists only a single abstract method.
 Lambda block expression: It means lambda expression with multiple statements.
 Generic functional interface: It is determined as when a lambda expression is unable to define the
type of parameters.
 Passing lambda expression as arguments: It is a lambda expression is generally used when the
datatype provides a target.
 Exception: It is a lambda expression is a feature to test lambda.
 Variables: They are generally defined as a name to the memory locations that keeps a value of a
specific datatype.
 Constructor reference: It can be assigned to any functional interface.

14
UNIT 13: Lambda Expressions JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

13.13 SELF-ASSESSMENT QUESTIONS

A. Essay Type Questions


1. A lambda expression refers to a method that has no name; no access specifier private. What do you
understand by the term lambda expression?
2. A lambda block means lambda expression with multiple statements. Describe the concept of block
lambda expression briefly.
3. In terms of passing lambda expression as arguments, a lambda expression is generally used when
the datatype provides a target. Determine the importance of passing a lambda expression as
arguments in java.
4. A lambda expression is used only for calling an existing method by using its name. Evaluate the
concept of a method reference in brief.
5. A functional interface is an interface in which there is exactly one abstract method. How predefined
functional interfaces work in java?

13.14 ANSWERS AND HINTS FOR SELF-ASSESSMENT QUESTIONS

A. Hints for Essay Type Questions


1. 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. Refer to Section Introduction
2. A lambda block means lambda expression with multiple statements. The multiple statements
containing code are called expression bodies. Refer to Section Block Lambda Expressions
3. In terms of passing lambda expression as arguments, a lambda expression is generally used when
the datatype provides a target in the context the when lambda expression passed as an argument.
Refer to Section Passing Lambda Expression as Arguments
4. As discussed earlier, you can use lambda expressions for creating anonymous methods. Sometimes,
a lambda expression is used only for calling an existing method by using its name but not for
performing operations. Refer to Section Method References
5. A functional interface is an interface in which there is exactly one abstract method. Some examples of
functional interface are java. util. comparator, java. lang. Runnable, jamaats. event. ActionListener,
java. util. concurrent. Callable, java. security. PriviligedAction, etc. Refer to Section Predefined
Functional Interfaces

@ 13.15 POST-UNIT READING MATERIAL

 https://www.journaldev.com/37273/java-14-features
 http://dig.cs.illinois.edu/papers/Mazinanian_OOPSLA_2017.pdf

13.16 TOPICS FOR DISCUSSION FORUMS

 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

You might also like