SlideShare a Scribd company logo
Unit-3
Java New Features: Functional Interfaces, Lambda Expression, Method
References, Stream API, Default Methods, Static Method, Base64 Encode and
Decode, ForEach Method, Try-with resources, Type Annotations, Repeating
Annotations, Java Module System, Diamond Syntax with Inner Anonymous
Class, Local Variable Type Inference, Switch Expressions, Yield Keyword, Text
Blocks, Records, Sealed Classes
Functional Interfaces in Java
•Java has forever remained an Object-Oriented Programming language.
•By object-oriented programming language, we can declare that
everything present in the Java programming language rotates
throughout the Objects, except for some of the primitive data types
and primitive methods for integrity and simplicity.
•There are no solely functions present in a programming language
called Java.
•Functions in the Java programming language are part of a class, and if
someone wants to use them, they have to use the class or object of the
class to call any function.
Java Functional Interfaces
• A functional interface is an interface that contains only one abstract method.
• They can have only one functionality to exhibit.
• From Java 8 onwards, lambda expressions can be used to represent the instance of
a functional interface.
• A functional interface can have any number of default methods.
• Example - Runnable, ActionListener, and Comparable
• Functional Interface is additionally recognized as Single Abstract Method
Interfaces.
• In short, they are also known as SAM interfaces. Functional interfaces in Java are
the new feature that provides users with the approach of fundamental
programming.
• Functional interfaces are included in Java SE 8 with Lambda expressions and Method
references in order to make code more readable, clean, and straightforward.
• Functional interfaces are interfaces that ensure that they include precisely only one
abstract method.
• Functional interfaces are used and executed by representing the interface with
an annotation called @FunctionalInterface.
• As described earlier, functional interfaces can contain only one abstract method.
However, they can include any quantity of default and static methods.
• In Functional interfaces, there is no need to use the abstract keyword as it is optional to
use the abstract keyword because, by default, the method defined inside the interface is
abstract only.
• We can also call Lambda expressions as the instance of functional interface.
Lambda Expressions
•Lambda Expressions were added in Java 8.
•A lambda expression is a short block of code which
takes in parameters and returns a value.
•Lambda expressions are similar to methods, but they
do not need a name and they can be implemented right
in the body of a method.
Lambda Expression in Java
•In Java, Lambda expressions basically express instances of
functional interfaces (An interface with a single abstract method
is called a functional interface). Lambda Expressions in Java
are the same as lambda functions which are the short block of
code that accepts input as parameters and returns a resultant
value. Lambda Expressions are recently included in Java SE 8.
Unit-3.pptx.pdf java api knowledge apiii
Unit-3.pptx.pdf java api knowledge apiii
Java Lambda Expression Syntax
(argument-list) → {body}
Java lambda expression is consisted of three components.
1 Argument-list: It can be empty or non-empty as well.
2 Arrow-token: It is used to link arguments-list and body of expression.
3 Body: It contains expressions and statements for lambda expression.
No Parameter Syntax
() → {
//Body of no parameter lambda
}
One Parameter Syntax
(p1) → {
//Body of single parameter lambda
}
Two Parameter Syntax
(p1,p2) → { //Body of multiple parameter lambda }
Example:
Unit-3.pptx.pdf java api knowledge apiii
Unit-3.pptx.pdf java api knowledge apiii
// Java program to demonstrate lambda expressions to
// implement a user defined functional interface(one parameter).
@FunctionalInterface
interface Square {
int calculate(int x);
}
class Test {
public static void main(String args[])
{
int a = 5;
// lambda expression to define the calculate method
Square s = (int x) -> x * x;
// parameter passed and return type must be
// same as defined in the prototype
int ans = s.calculate(a);
System.out.println(ans);
}
}
Java Lambda Expression Example: Multiple
Parameters
interface Addable{
int add(int a,int b);
}
public class LambdaExpressionExample5
public static void main(String[] args) {
// Multiple parameters in lambda expression
Addable ad1a,ba+b;
System.out.println(ad1.add(10,20));
// Multiple parameters with data type in lambda expression
Addable ad2int a,int b)→(a+b);
System.out.println(ad2.add(100,200));
}
}
Test it No
Output:
30 300
Java Lambda Expression Example: with or
without return keyword
interface Addable{
int add(int a,int b);
}
public class LambdaExpressionExample6 {
public static void main(String[] args) {
// Lambda expression without return keyword.
Addable ad1a,ba+b;
System.out.println(ad1.add(10,20));
// Lambda expression with return keyword.
Addable ad2int a,int b)→{
return (a+b);
};
System.out.println(ad2.add(100,200));
}
}
Test it No
Output:
30 300
// Define a functional interface with a single abstract
method
@FunctionalInterface
interface ArithmeticOperation {
int operate(int a, int b);
}
public class Main {
public static void main(String[] args) {
// Implement the interface using a lambda
expression for addition
ArithmeticOperation add = (a, b) -> a + b;
// Implement the interface using a lambda
expression for subtraction
ArithmeticOperation subtract = (a, b) -> a - b;
// Implement the interface using a lambda
expression for multiplication
ArithmeticOperation multiply = (a, b) -> a * b;
// Implement the interface using a lambda expression
for division
ArithmeticOperation divide = (a, b) -> {
if (b == 0) {
throw new ArithmeticException("Division by
zero");
}
return a / b;
};
// Using the implemented lambda expressions
System.out.println("Addition: " +
add.operate(5,3));
System.out.println("Subtraction: " +
subtract.operate(5, 3));
System.out.println("Multiplication: " +
multiply.operate(5, 3));
System.out.println("Division: " + divide.operate(5,
3));
}
}
• ArithmeticOperation is a functional interface with a single abstract method
operate, which takes two integer arguments and returns an integer. This
method can be implemented to perform any binary operation on two
integers.
• Lambda expressions provide a clear and concise way to implement
functional interfaces without the need for anonymous classes. A lambda
expression consists of a set of parameters, an arrow (->), and a body.
• Addition:
ArithmeticOperation add = (a, b) -> a + b;
Here, add is an instance of ArithmeticOperation where the operate
method is implemented to return the sum of a and b.
• Subtraction:
ArithmeticOperation subtract = (a, b) -> a - b;
Similar to addition, this lambda expression subtracts b from a.
• Multiplication:
ArithmeticOperation multiply = (a, b) -> a * b;
This multiplies the two arguments.
• Division:
ArithmeticOperation divide = (a, b) -> {
if (b == 0) {
throw new ArithmeticException("Division by zero");
}
return a / b;
};
• This is a more complex lambda expression that first checks if the divisor b is zero,
throwing an ArithmeticException if true, otherwise it returns the division of a by b.
4. Using Lambda Expressions
•In the main method, these lambda expressions are used like any other
object:
• System.out.println("Addition: " + add.operate(5, 3));
• System.out.println("Subtraction: " + subtract.operate(5, 3));
• System.out.println("Multiplication: " + multiply.operate(5, 3));
• System.out.println("Division: " + divide.operate(5, 3));
•Each operate method of different instances (add, subtract, multiply,
divide) is called with specific arguments (5 and 3). The lambda
expressions defined for each instance determine the operation
performed.
Method References in java
•Method references are a feature of Java 8 that allows you to
refer to a method without having to call it. This can be useful in
a number of situations, such as when you need to pass a
method as an argument to another method.
•There are four types of method references:
• Reference to a static method
• Reference to an instance method of a particular object
• Reference to an instance method of an arbitrary object of a particular
type
• Reference to a constructor
Static method reference.
•// This method reference refers to the static method `Math.max()`
•MethodReference<Double> max = Math::max;
•// This will print the maximum of 10 and 20
•System.out.println(max.apply(10, 20));
Instance method reference of a
particular object:
•// This method reference refers to the instance method
`String.toUpperCase()`
•MethodReference<String> toUpperCase = String::toUpperCase;
•// This will print the string "HELLO"
•System.out.println(toUpperCase.apply("hello"));
Instance method reference of an
arbitrary object of a particular type:
•// This method reference refers to the instance method `List.sort()`
•MethodReference<List<String>> sort = List::sort;
•// This will sort the list in ascending order
•List<String> names = Arrays.asList("John", "Mary", "Bob");
•sort.apply(names);
•// This will print the sorted list
•System.out.println(names);
Constructor reference.
•// This method reference refers to the constructor for the `Person`
class
•MethodReference<Person> personConstructor = Person::new;
•// This will create a new Person object
•Person person = personConstructor.apply("John Doe");
•// This will print the person's name
•System.out.println(person.getName());
Method references
• Method references can be used in a number of other situations, such as
when you need to pass a method as an argument to a lambda expression.
For example, the following code shows how to use a method reference to
pass the Math.max() method to a lambda expression:
• // This lambda expression uses the `Math.max()` method to find the
maximum of two numbers
• Function<Integer, Integer> maxFunction = (a, b) -> Math.max(a, b);
• // This will print the maximum of 10 and 20
• System.out.println(maxFunction.apply(10, 20));
• Methods allow us to reuse the code without retyping the code.
Syntax and Usage
A method reference is described using the :: (double colon) symbol.
The general syntax is one of the following forms:
•Reference to a static method: ContainingClass::staticMethodName
•Reference to an instance method of a particular object:
instance::instanceMethodName
•Reference to an instance method of an arbitrary object of a particular
type:ContainingType::methodName
•Reference to a constructor: ClassName::new
Examples
1. Reference to a Static Method
• import java.util.function.Function;
• public class StaticMethodReferenceExample {
• public static void main(String[] args) {
• Function<String, Integer> stringLength = String::length;
• int length = stringLength.apply("Hello, world!");
• System.out.println("Length of the string: " + length);
• }
• }
• In this example, String::length is a static method reference that refers
to the length() method of the String class.
2. Reference to an Instance Method of a Particular Object
import java.util.function.Supplier;
public class ParticularObjectInstanceMethodReferenceExample {
String name = "Java";
public static void main(String[] args) {
ParticularObjectInstanceMethodReferenceExample obj = new
ParticularObjectInstanceMethodReferenceExample();
Supplier<String> getName = obj::getName; // Method reference to a specific object's
method
String name = getName.get();
System.out.println("Name: " + name);
}
public String getName() {
return name;
}
}
Here, obj::getName refers to the getName() method of the specific obj instance.
3. Reference to an Instance Method of an Arbitrary Object of a Particular Type
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
public class ArbitraryObjectInstanceMethodReferenceExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
Consumer<String> printName = System.out::println; // Method reference to an arbitrary String
object's method
names.forEach(printName);
}
}
In this case, System.out::println refers to the println() method that can be called on any String object.
4. Reference to a Constructor
import java.util.function.Supplier;
import java.util.ArrayList;
public class ConstructorReferenceExample {
public static void main(String[] args) {
Supplier<ArrayList<String>> createList = ArrayList::new;
ArrayList<String> names = createList.get();
names.add("David");
names.add("Eve");
System.out.println(names);
}
}
ArrayList::new is a constructor reference that allows you to create new
ArrayList objects.
What is the Stream API?
• The Stream API is a framework introduced in Java 8 that enables you to express
operations on collections (lists, arrays, etc.) as a series of transformations. It's
designed to make your code more concise, readable, and potentially more
efficient by leveraging parallelism.
Key Concepts
• Stream: A sequence of elements from a source (e.g., collection, array, file) that
supports aggregate operations. It doesn't store the elements themselves.
• Pipeline: A sequence of stream operations (intermediate and terminal) that are
chained together.
• Intermediate Operations: These operations (like filter, map, sorted) transform a
stream into another stream. They're lazily evaluated, meaning they don't execute
until a terminal operation is called.
• Terminal Operations: These operations (like forEach, collect, count) produce a
final result or side effect, consuming the stream in the process.
Creating Streams
•From Collections: List<String> names = ...; Stream<String>
nameStream = names.stream();
•From Arrays: int[] numbers = ...; IntStream numberStream =
Arrays.stream(numbers);
•From Values: Stream<String> stream = Stream.of("Java", "Python",
"C++");
•From a Function: Stream.iterate(0, n -> n + 2).limit(10); (Creates a
stream of even numbers)
Stream API
•Stream operations are expressed in a declarative manner—they
describe what to do rather than how to do it.
•Key Features of Stream API
•Declarative Programming: Allows you to express operations
on data sequences succinctly and clearly.
•Pipeline Processing: Streams can be pipelined to achieve
greater efficiency. Operations can be executed lazily to avoid
processing all data until it is necessary.
•Parallelism: Streams support parallel processing, which can
lead to significant performance improvements in multi-core
environments.
Components of the Stream API
•The Stream API consists of a source, zero or more intermediate
operations, and a terminal operation:
• Source: Streams can be created from collections, arrays, files, and other data
sources.
• Intermediate Operations: Transform the stream into another one, such as
filter, map, and sorted.
• Terminal Operations: Produce a result or side-effect, such as forEach, collect,
or reduce.
Common Stream Operations
•Creating a Stream
•From a collection: Collection.stream() or Collection.parallelStream()
•From an array: Arrays.stream(T[] array)
•Of specific elements: Stream.of(T... values)
Intermediate Operations
•filter(Predicate<T>): Returns a stream consisting of elements that
match the given predicate.
•map(Function<T, R>): Returns a stream where each element is
replaced by the result of applying a function to it.
•sorted(): Returns a stream with elements sorted according to natural
order or a provided comparator.
Terminal Operations
•forEach(Consumer<T>): Performs an action for each element of the
stream.
•collect(Collectors): Transforms the elements into a different form,
often a collection like a List or a Map.
•reduce(BinaryOperator<T>): Combines elements of the stream
sequentially and returns an optional reduced value.
Example: Using the Stream API
import java.util.*;
import java.util.stream.*;
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
public class Stream {
public static void main(String[] args) {
List<Person> people = Arrays.asList(
new Person("John", 30),
new Person("Jane", 25),
new Person("Greg", 18),
new Person("Sara", 20),
new Person("Harold", 40)
);
• // Example 1: Filter and print names of people
older than 25
• System.out.println("People older than
25:");
• people.stream()
• .filter(p -> p.getAge() > 25)
• .forEach(p ->
System.out.println(p.getName()));
• // Example 2: Calculate average age of all
people
• double averageAge = people.stream()
• .mapToInt(Person::getAge)
• .average()
• .getAsDouble();
• System.out.println("Average age: " +
averageAge);
• // Example 3: Check if there is anyone younger
than 18
• boolean anyYoungerThan18 =
people.stream()
• .anyMatch(p ->
p.getAge() < 18);
• System.out.println("Any person younger
than 18: " + anyYoungerThan18);
• // Example 4: Collect names into a list
• List<String> names = people.stream()
• .map(Person::getName)
• .collect(Collectors.toList());
• System.out.println("Names: " + names);
•// Example 5: Get a list of all ages
sorted
List<Integer> ages = people.stream()
.map(Person::getAge)
.sorted()
.collect(Collectors.toList());
System.out.println("Sorted ages: " +
ages);
}
}
•People older than 25:
•John
•Harold
•Average age: 26.6
•Any person younger
than 18: false
•Names: [John, Jane,
Greg, Sara, Harold]
•Sorted ages: [18, 20,
25, 30, 40]

More Related Content

Similar to Unit-3.pptx.pdf java api knowledge apiii (20)

PPTX
Java 8 Intro - Core Features
GlobalLogic Ukraine
 
PDF
Java 8
Sheeban Singaram
 
PDF
Functional programming in java 8 by harmeet singh
Harmeet Singh(Taara)
 
PPTX
Java 8 lambda
Manav Prasad
 
PDF
Charles Sharp: Java 8 Streams
jessitron
 
PDF
Java 8
vilniusjug
 
PDF
Lambda Expression For anyone that needs Java Lambda notes
shreyansh15388
 
PPT
Lambdas
malliksunkara
 
PPTX
Java 8 Functional Programming - I
Ugur Yeter
 
PPTX
java8
Arik Abulafya
 
PPT
Java findamentals1
Todor Kolev
 
PPT
Java findamentals1
Todor Kolev
 
PPT
Java findamentals1
Todor Kolev
 
PPTX
Java 8 - An Overview
Indrajit Das
 
PPTX
Lambdas, Collections Framework, Stream API
Prabu U
 
PPTX
Lambda Expressions Java 8 Features usage
AsmaShaikh478737
 
PPTX
Java 8
Sudipta K Paik
 
PPT
14274730 (1).ppt
aptechaligarh
 
PPTX
Java gets a closure
Tomasz Kowalczewski
 
PPTX
Java8: what's new and what's hot
Sergii Maliarov
 
Java 8 Intro - Core Features
GlobalLogic Ukraine
 
Functional programming in java 8 by harmeet singh
Harmeet Singh(Taara)
 
Java 8 lambda
Manav Prasad
 
Charles Sharp: Java 8 Streams
jessitron
 
Java 8
vilniusjug
 
Lambda Expression For anyone that needs Java Lambda notes
shreyansh15388
 
Lambdas
malliksunkara
 
Java 8 Functional Programming - I
Ugur Yeter
 
Java findamentals1
Todor Kolev
 
Java findamentals1
Todor Kolev
 
Java findamentals1
Todor Kolev
 
Java 8 - An Overview
Indrajit Das
 
Lambdas, Collections Framework, Stream API
Prabu U
 
Lambda Expressions Java 8 Features usage
AsmaShaikh478737
 
14274730 (1).ppt
aptechaligarh
 
Java gets a closure
Tomasz Kowalczewski
 
Java8: what's new and what's hot
Sergii Maliarov
 

Recently uploaded (20)

PPTX
How to Create Odoo JS Dialog_Popup in Odoo 18
Celine George
 
PDF
Dimensions of Societal Planning in Commonism
StefanMz
 
PPTX
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
PPT
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
PPTX
How to Handle Salesperson Commision in Odoo 18 Sales
Celine George
 
PDF
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
PDF
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
PDF
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
PDF
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
PPTX
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
PPTX
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PPTX
Neurodivergent Friendly Schools - Slides from training session
Pooky Knightsmith
 
PPT
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
PDF
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
PDF
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
PPTX
GRADE-3-PPT-EVE-2025-ENG-Q1-LESSON-1.pptx
EveOdrapngimapNarido
 
PDF
The Different Types of Non-Experimental Research
Thelma Villaflores
 
PPTX
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
PPTX
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
How to Create Odoo JS Dialog_Popup in Odoo 18
Celine George
 
Dimensions of Societal Planning in Commonism
StefanMz
 
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
How to Handle Salesperson Commision in Odoo 18 Sales
Celine George
 
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
Neurodivergent Friendly Schools - Slides from training session
Pooky Knightsmith
 
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
GRADE-3-PPT-EVE-2025-ENG-Q1-LESSON-1.pptx
EveOdrapngimapNarido
 
The Different Types of Non-Experimental Research
Thelma Villaflores
 
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
Ad

Unit-3.pptx.pdf java api knowledge apiii

  • 1. Unit-3 Java New Features: Functional Interfaces, Lambda Expression, Method References, Stream API, Default Methods, Static Method, Base64 Encode and Decode, ForEach Method, Try-with resources, Type Annotations, Repeating Annotations, Java Module System, Diamond Syntax with Inner Anonymous Class, Local Variable Type Inference, Switch Expressions, Yield Keyword, Text Blocks, Records, Sealed Classes
  • 2. Functional Interfaces in Java •Java has forever remained an Object-Oriented Programming language. •By object-oriented programming language, we can declare that everything present in the Java programming language rotates throughout the Objects, except for some of the primitive data types and primitive methods for integrity and simplicity. •There are no solely functions present in a programming language called Java. •Functions in the Java programming language are part of a class, and if someone wants to use them, they have to use the class or object of the class to call any function.
  • 3. Java Functional Interfaces • A functional interface is an interface that contains only one abstract method. • They can have only one functionality to exhibit. • From Java 8 onwards, lambda expressions can be used to represent the instance of a functional interface. • A functional interface can have any number of default methods. • Example - Runnable, ActionListener, and Comparable • Functional Interface is additionally recognized as Single Abstract Method Interfaces. • In short, they are also known as SAM interfaces. Functional interfaces in Java are the new feature that provides users with the approach of fundamental programming.
  • 4. • Functional interfaces are included in Java SE 8 with Lambda expressions and Method references in order to make code more readable, clean, and straightforward. • Functional interfaces are interfaces that ensure that they include precisely only one abstract method. • Functional interfaces are used and executed by representing the interface with an annotation called @FunctionalInterface. • As described earlier, functional interfaces can contain only one abstract method. However, they can include any quantity of default and static methods. • In Functional interfaces, there is no need to use the abstract keyword as it is optional to use the abstract keyword because, by default, the method defined inside the interface is abstract only. • We can also call Lambda expressions as the instance of functional interface.
  • 5. Lambda Expressions •Lambda Expressions were added in Java 8. •A lambda expression is a short block of code which takes in parameters and returns a value. •Lambda expressions are similar to methods, but they do not need a name and they can be implemented right in the body of a method.
  • 6. Lambda Expression in Java •In Java, Lambda expressions basically express instances of functional interfaces (An interface with a single abstract method is called a functional interface). Lambda Expressions in Java are the same as lambda functions which are the short block of code that accepts input as parameters and returns a resultant value. Lambda Expressions are recently included in Java SE 8.
  • 9. Java Lambda Expression Syntax (argument-list) → {body} Java lambda expression is consisted of three components. 1 Argument-list: It can be empty or non-empty as well. 2 Arrow-token: It is used to link arguments-list and body of expression. 3 Body: It contains expressions and statements for lambda expression. No Parameter Syntax () → { //Body of no parameter lambda } One Parameter Syntax (p1) → { //Body of single parameter lambda } Two Parameter Syntax (p1,p2) → { //Body of multiple parameter lambda }
  • 13. // Java program to demonstrate lambda expressions to // implement a user defined functional interface(one parameter). @FunctionalInterface interface Square { int calculate(int x); } class Test { public static void main(String args[]) { int a = 5; // lambda expression to define the calculate method Square s = (int x) -> x * x; // parameter passed and return type must be // same as defined in the prototype int ans = s.calculate(a); System.out.println(ans); } }
  • 14. Java Lambda Expression Example: Multiple Parameters interface Addable{ int add(int a,int b); } public class LambdaExpressionExample5 public static void main(String[] args) { // Multiple parameters in lambda expression Addable ad1a,ba+b; System.out.println(ad1.add(10,20)); // Multiple parameters with data type in lambda expression Addable ad2int a,int b)→(a+b); System.out.println(ad2.add(100,200)); } } Test it No Output: 30 300
  • 15. Java Lambda Expression Example: with or without return keyword interface Addable{ int add(int a,int b); } public class LambdaExpressionExample6 { public static void main(String[] args) { // Lambda expression without return keyword. Addable ad1a,ba+b; System.out.println(ad1.add(10,20)); // Lambda expression with return keyword. Addable ad2int a,int b)→{ return (a+b); }; System.out.println(ad2.add(100,200)); } } Test it No Output: 30 300
  • 16. // Define a functional interface with a single abstract method @FunctionalInterface interface ArithmeticOperation { int operate(int a, int b); } public class Main { public static void main(String[] args) { // Implement the interface using a lambda expression for addition ArithmeticOperation add = (a, b) -> a + b; // Implement the interface using a lambda expression for subtraction ArithmeticOperation subtract = (a, b) -> a - b; // Implement the interface using a lambda expression for multiplication ArithmeticOperation multiply = (a, b) -> a * b; // Implement the interface using a lambda expression for division ArithmeticOperation divide = (a, b) -> { if (b == 0) { throw new ArithmeticException("Division by zero"); } return a / b; }; // Using the implemented lambda expressions System.out.println("Addition: " + add.operate(5,3)); System.out.println("Subtraction: " + subtract.operate(5, 3)); System.out.println("Multiplication: " + multiply.operate(5, 3)); System.out.println("Division: " + divide.operate(5, 3)); } }
  • 17. • ArithmeticOperation is a functional interface with a single abstract method operate, which takes two integer arguments and returns an integer. This method can be implemented to perform any binary operation on two integers. • Lambda expressions provide a clear and concise way to implement functional interfaces without the need for anonymous classes. A lambda expression consists of a set of parameters, an arrow (->), and a body. • Addition: ArithmeticOperation add = (a, b) -> a + b; Here, add is an instance of ArithmeticOperation where the operate method is implemented to return the sum of a and b. • Subtraction: ArithmeticOperation subtract = (a, b) -> a - b; Similar to addition, this lambda expression subtracts b from a.
  • 18. • Multiplication: ArithmeticOperation multiply = (a, b) -> a * b; This multiplies the two arguments. • Division: ArithmeticOperation divide = (a, b) -> { if (b == 0) { throw new ArithmeticException("Division by zero"); } return a / b; }; • This is a more complex lambda expression that first checks if the divisor b is zero, throwing an ArithmeticException if true, otherwise it returns the division of a by b.
  • 19. 4. Using Lambda Expressions •In the main method, these lambda expressions are used like any other object: • System.out.println("Addition: " + add.operate(5, 3)); • System.out.println("Subtraction: " + subtract.operate(5, 3)); • System.out.println("Multiplication: " + multiply.operate(5, 3)); • System.out.println("Division: " + divide.operate(5, 3)); •Each operate method of different instances (add, subtract, multiply, divide) is called with specific arguments (5 and 3). The lambda expressions defined for each instance determine the operation performed.
  • 20. Method References in java •Method references are a feature of Java 8 that allows you to refer to a method without having to call it. This can be useful in a number of situations, such as when you need to pass a method as an argument to another method. •There are four types of method references: • Reference to a static method • Reference to an instance method of a particular object • Reference to an instance method of an arbitrary object of a particular type • Reference to a constructor
  • 21. Static method reference. •// This method reference refers to the static method `Math.max()` •MethodReference<Double> max = Math::max; •// This will print the maximum of 10 and 20 •System.out.println(max.apply(10, 20));
  • 22. Instance method reference of a particular object: •// This method reference refers to the instance method `String.toUpperCase()` •MethodReference<String> toUpperCase = String::toUpperCase; •// This will print the string "HELLO" •System.out.println(toUpperCase.apply("hello"));
  • 23. Instance method reference of an arbitrary object of a particular type: •// This method reference refers to the instance method `List.sort()` •MethodReference<List<String>> sort = List::sort; •// This will sort the list in ascending order •List<String> names = Arrays.asList("John", "Mary", "Bob"); •sort.apply(names); •// This will print the sorted list •System.out.println(names);
  • 24. Constructor reference. •// This method reference refers to the constructor for the `Person` class •MethodReference<Person> personConstructor = Person::new; •// This will create a new Person object •Person person = personConstructor.apply("John Doe"); •// This will print the person's name •System.out.println(person.getName());
  • 25. Method references • Method references can be used in a number of other situations, such as when you need to pass a method as an argument to a lambda expression. For example, the following code shows how to use a method reference to pass the Math.max() method to a lambda expression: • // This lambda expression uses the `Math.max()` method to find the maximum of two numbers • Function<Integer, Integer> maxFunction = (a, b) -> Math.max(a, b); • // This will print the maximum of 10 and 20 • System.out.println(maxFunction.apply(10, 20)); • Methods allow us to reuse the code without retyping the code.
  • 26. Syntax and Usage A method reference is described using the :: (double colon) symbol. The general syntax is one of the following forms: •Reference to a static method: ContainingClass::staticMethodName •Reference to an instance method of a particular object: instance::instanceMethodName •Reference to an instance method of an arbitrary object of a particular type:ContainingType::methodName •Reference to a constructor: ClassName::new
  • 27. Examples 1. Reference to a Static Method • import java.util.function.Function; • public class StaticMethodReferenceExample { • public static void main(String[] args) { • Function<String, Integer> stringLength = String::length; • int length = stringLength.apply("Hello, world!"); • System.out.println("Length of the string: " + length); • } • } • In this example, String::length is a static method reference that refers to the length() method of the String class.
  • 28. 2. Reference to an Instance Method of a Particular Object import java.util.function.Supplier; public class ParticularObjectInstanceMethodReferenceExample { String name = "Java"; public static void main(String[] args) { ParticularObjectInstanceMethodReferenceExample obj = new ParticularObjectInstanceMethodReferenceExample(); Supplier<String> getName = obj::getName; // Method reference to a specific object's method String name = getName.get(); System.out.println("Name: " + name); } public String getName() { return name; } } Here, obj::getName refers to the getName() method of the specific obj instance.
  • 29. 3. Reference to an Instance Method of an Arbitrary Object of a Particular Type import java.util.Arrays; import java.util.List; import java.util.function.Consumer; public class ArbitraryObjectInstanceMethodReferenceExample { public static void main(String[] args) { List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); Consumer<String> printName = System.out::println; // Method reference to an arbitrary String object's method names.forEach(printName); } } In this case, System.out::println refers to the println() method that can be called on any String object.
  • 30. 4. Reference to a Constructor import java.util.function.Supplier; import java.util.ArrayList; public class ConstructorReferenceExample { public static void main(String[] args) { Supplier<ArrayList<String>> createList = ArrayList::new; ArrayList<String> names = createList.get(); names.add("David"); names.add("Eve"); System.out.println(names); } } ArrayList::new is a constructor reference that allows you to create new ArrayList objects.
  • 31. What is the Stream API? • The Stream API is a framework introduced in Java 8 that enables you to express operations on collections (lists, arrays, etc.) as a series of transformations. It's designed to make your code more concise, readable, and potentially more efficient by leveraging parallelism. Key Concepts • Stream: A sequence of elements from a source (e.g., collection, array, file) that supports aggregate operations. It doesn't store the elements themselves. • Pipeline: A sequence of stream operations (intermediate and terminal) that are chained together. • Intermediate Operations: These operations (like filter, map, sorted) transform a stream into another stream. They're lazily evaluated, meaning they don't execute until a terminal operation is called. • Terminal Operations: These operations (like forEach, collect, count) produce a final result or side effect, consuming the stream in the process.
  • 32. Creating Streams •From Collections: List<String> names = ...; Stream<String> nameStream = names.stream(); •From Arrays: int[] numbers = ...; IntStream numberStream = Arrays.stream(numbers); •From Values: Stream<String> stream = Stream.of("Java", "Python", "C++"); •From a Function: Stream.iterate(0, n -> n + 2).limit(10); (Creates a stream of even numbers)
  • 33. Stream API •Stream operations are expressed in a declarative manner—they describe what to do rather than how to do it. •Key Features of Stream API •Declarative Programming: Allows you to express operations on data sequences succinctly and clearly. •Pipeline Processing: Streams can be pipelined to achieve greater efficiency. Operations can be executed lazily to avoid processing all data until it is necessary. •Parallelism: Streams support parallel processing, which can lead to significant performance improvements in multi-core environments.
  • 34. Components of the Stream API •The Stream API consists of a source, zero or more intermediate operations, and a terminal operation: • Source: Streams can be created from collections, arrays, files, and other data sources. • Intermediate Operations: Transform the stream into another one, such as filter, map, and sorted. • Terminal Operations: Produce a result or side-effect, such as forEach, collect, or reduce.
  • 35. Common Stream Operations •Creating a Stream •From a collection: Collection.stream() or Collection.parallelStream() •From an array: Arrays.stream(T[] array) •Of specific elements: Stream.of(T... values)
  • 36. Intermediate Operations •filter(Predicate<T>): Returns a stream consisting of elements that match the given predicate. •map(Function<T, R>): Returns a stream where each element is replaced by the result of applying a function to it. •sorted(): Returns a stream with elements sorted according to natural order or a provided comparator.
  • 37. Terminal Operations •forEach(Consumer<T>): Performs an action for each element of the stream. •collect(Collectors): Transforms the elements into a different form, often a collection like a List or a Map. •reduce(BinaryOperator<T>): Combines elements of the stream sequentially and returns an optional reduced value.
  • 38. Example: Using the Stream API import java.util.*; import java.util.stream.*; class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } } public class Stream { public static void main(String[] args) { List<Person> people = Arrays.asList( new Person("John", 30), new Person("Jane", 25), new Person("Greg", 18), new Person("Sara", 20), new Person("Harold", 40) );
  • 39. • // Example 1: Filter and print names of people older than 25 • System.out.println("People older than 25:"); • people.stream() • .filter(p -> p.getAge() > 25) • .forEach(p -> System.out.println(p.getName())); • // Example 2: Calculate average age of all people • double averageAge = people.stream() • .mapToInt(Person::getAge) • .average() • .getAsDouble(); • System.out.println("Average age: " + averageAge); • // Example 3: Check if there is anyone younger than 18 • boolean anyYoungerThan18 = people.stream() • .anyMatch(p -> p.getAge() < 18); • System.out.println("Any person younger than 18: " + anyYoungerThan18); • // Example 4: Collect names into a list • List<String> names = people.stream() • .map(Person::getName) • .collect(Collectors.toList()); • System.out.println("Names: " + names);
  • 40. •// Example 5: Get a list of all ages sorted List<Integer> ages = people.stream() .map(Person::getAge) .sorted() .collect(Collectors.toList()); System.out.println("Sorted ages: " + ages); } } •People older than 25: •John •Harold •Average age: 26.6 •Any person younger than 18: false •Names: [John, Jane, Greg, Sara, Harold] •Sorted ages: [18, 20, 25, 30, 40]