Day18 LambdaExpression
Day18 LambdaExpression
A Integer class
B Float class
C Primitive Types
Collections
D
A Integer class
B Float class
C Primitive Types
Collections
D
• An interface is declared with only one abstract method, then it is referred as Functional
Interface.
Along with the functional method, you can also add default and static method to functional
interface.
•Runnable
•ActionListener
•ItemListener
TNS India Foundation | ‹#›
Partners in Economic Transformation
Hook
•Lambda expression allows for creation and use of single method anonymous classes
instead of creating separate concrete class for functional interface
•They can accept zero or more parameters, any of which can be passed with or without type
specification.
•Then signature of lambda expression implementing Runnable interface will be () -> void.
Supplier: Supplier represent an operation through which we can generate new values
in the stream. Some of the methods in Stream that takes Supplier argument are:
● The function interface has four methods, mostly function used in map feature of stream
APIs.
R apply(T var1);
● we use consumers when we need to consume objects, the consumer takes an input
● Lambda expressions are an important addition to Java that greatly improves overall
maintainability, readability, and developer productivity.
● They can be applied in many different contexts, ranging from simple anonymous
functions to sorting and filtering Collections.
● Lambda expressions can be assigned to variables and then passed into other
objects.
● It allows developers to write cleaner, shorter more readable, and reusable code.
Q1. Which of the following annotations can be used to ensure that an interface is a
functional interface?
A @Functional
B @FunctionalInterface
C @FunctionalClass
D @FunctionalType
Q1. Which of the following annotations can be used to ensure that an interface is a
functional interface?
A @Functional
B @FunctionalInterface
C @FunctionalClass
D @FunctionalType
Q2.In Java, which method is used to apply a lambda expression to each element of
a stream?
A forEach()
B map()
C filter()
D reduce()
Q2.In Java, which method is used to apply a lambda expression to each element of
a stream?
A forEach()
B map()
C filter()
D reduce()
Objective:
Create a simple task scheduler application using Java and lambda expressions. The
task scheduler should allow users to schedule tasks to be executed at specific intervals.
Requirements:
Task Interface:
Define a functional interface called Task with a single method execute() representing
the task to be performed.
● Implement a class called TaskScheduler that will manage the scheduling of tasks.
● The TaskScheduler class should have a method scheduleTask(Task task, int
interval) to schedule a task to be executed at the specified interval (in seconds).
● Use lambda expressions to represent tasks when scheduling.
Testing: