SlideShare una empresa de Scribd logo
1 de 28
Descargar para leer sin conexión
Functional Programming
In JAVA
By Harmeet Singh(Taara)
(Java EE Developer)
Email: harmeetsingh.0013@gmail.com
Blog: http://harmeetsingh13.blogspot.in
Skype: harmeetsingh0013
Contact: Via Email or Skype
➢ Introduction
➢ Functional Programming.
➢ Single Abstract Method(SAM).
➢ Functional Interface.
➢ Declare Lambda Expressions.
➢ Code Refactor Using Lambda Expression.
➢ Predefined Functional Interfaces in Java 8.
➢ User Defined Functional Interface in Java 8.
➢ Type Inference.
➢ Translation Of Lambda Expressions.
➢ Runtime Translation Strategies.
➢ Leftover: The Things We Didn’t Cover.
Contents
Acknowledgement
❖ Thanks To My Parents.
❖ Thanks To All Who Support Me or Not.
❖ Dedicated To My Teacher “Mr. Kapil Sakhuja”.
Introduction
In Java 8, the functional programming is the important
evolution in Object Oriented Programming world of Java.
Now, Java use lambdas, Simple Abstract Method (SAM)
etc for allow functional programming in Object Oriented
World.
There are so many new features are added in Java 8 like
Streams, Default methods etc. But Today’s we only
discuss about “Functional Programming In Java”.
What is Functional Programming ?
Immutable Object: In Object Oriented and Functional
Programming, An Immutable Object is an object whose
state cannot be modified after it is created.
Functional Programming: Functional Programming
involves writing code that does not change state. One of
the key feature of Functional Programming is the First-
Class Functions.
Single Abstract Method(SAM)
Interfaces have one Abstract Method are called SAM.
In Java there are lots of interfaces which only have one
abstract method(by default interface have abstract
method) like Runnable, Closeable etc.
These Single Abstract Method(SAM) Interfaces are also
called “Functional Interface”.
Functional Interface
Functional Interface: In Java 8, If Functional Interface
have more than one methods, one is different and rest of
the methods have same signature of Object class
methods. These types of Interfaces also called Functional
Interfaces like Comparator etc in Java.
If interface have one abstract method and one or more
than one Default and Static methods are also called
Functional Interface.
Declare Lambda Expression
Syntax :
lambda = ArgList “->” Body
ArgList = Identifier && Body = Expression
Examples:
(int x, int y) -> { return x+y }
(x, y) -? { return x+y }
(x) -> { return x+1 }
() -> { System.out.println(“Hello World”) }
Code Refactoring Using Lambda
Predefined Functional Interfaces in Java 8
In Java 8, There are lots of Predefined Functional
Interface, But today’s we only cover some important
Functional interfaces are :-
Predefined Functional Interfaces in Java 8
Predicate<T>: Represents a predicate (boolean-value-
function) of one argument.
Example:
Predefined Functional Interfaces in Java 8
Consumer<T>: Represents an operation that accept a
single input argument and returns no result.
Example:
Predefined Functional Interfaces in Java 8
Function<T, R>: Represents a function that accept a one
argument and produces a result.
Example:
Predefined Functional Interfaces in Java 8
Supplier<T>: Represents a supplier of results
Example:
Predefined Functional Interfaces in Java 8
UnaryOperator<T>: Represents an operations on a single
operands that produces a result of the same type as its
operand.
Example:
Predefined Functional Interfaces in Java 8
BinaryOperator<T, T>: Represents an operations upon
two operands of same type, producing a result of the
same type as the operands.
Example:
User Defined Functional Interfaces In Java 8
IN Java 8, it is also possible to create our custom user
define Functional Interface with the help of
“@FunctionalInterface” annotation. Our Functional
Interfaces also have default methods and static methods.
@FunctionalInterface: @FunctionalInterface annotation
indicates that the type declaration is intended to be a
functional interface, as defined by Java Language
Specification.
User Defined Functional Interfaces In Java 8
Example:
Type Inference
Type Inference is not the new topic in Java. In Java 7 we
create the Collections object with the help of Diamond
Operator(<>) like :
List<Integer> list = new ArrayList<>();
Under the hood of this code, Compiler use the “Type
Inference” technique. In this compiler pick the type
information from the left side of type declaration.
Type Inference
For Lambda expressions in Java 8, compiler use the same
“Type Inference” technique with some improvements.
Examples:
Predicate<Integer> predicate = (x) -> x > 5; //code
compile
Predicate predicate = (x) -> x > 5; // Compile time error
// Predicate is a raw type. References to generic type
//Predicate<T> should be parameterized
Translation Of Lambda Expression
Translate the lambda expression to bytecode is major
challenge for Java, because the important thing is to
maintain backward compatibility in bytecode. There are
so many challenges were faced for conversion like:
1. How to deal with Functional Interfaces?
2. For Lambdas use Inner classes?
3. Maintain Lambda information at runtime? etc.
Translation Of Lambda Expression
There are so many things are used and maintain for
lambdas in JVM, But for JVM the lambdas are not a new,
Because some languages are already use JVM for Runtime
Environment that have “Lambda Expression” like
Groovy, Scala, Clojure etc.
Today we only discuss the brief steps for translate Lambda
Expression after compilation.
Translation Of Lambda Expression
Followings are the Steps:
➔ Read “Lambda Expression” and desugars the lambda
body into a method whose argument list and return
type match that of “Lambda Expression”.
Example :
list.forEach( s -> { System.out.println(s); } );
//before compile
static void lambda$1(String s) { //After compile
System.out.println(s);
}
Translation Of Lambda Expression
Followings are the Steps:
➔ At the point at which the “Lambda Expression” would
be captured, it generates an “invokedynamic”
CallSite like :
list.forEach( s -> { System.out.println(s); } );
list.forEach( [lambda for lambda$1 as Block] );
Translation Of Lambda Expression
Followings are the Steps:
➔ This CallSite is called Lambda Factory for Given
Lambda.
➔ The Dynamic Arguments to the lambda factory are the
values captured from lexical scope.
➔ The Bootstrap Method for “Lambda Factory” is called
“Lambda Metafactory”.
Runtime Translation Strategies
➔ Generate Inner Classes Dynamically.
➔ Generate per-SAM wrapper class
◆ One per SAM type, not per lambda expression
◆ Use method handles for invocation.
◆ Use ClassValue to cache wrapper for SAM.
➔ Use Dynamic Proxies.
➔ Use MethodHandleProxies.asInterfaceInstance.
➔ Use VM private API to build object from scratch.
Leftover: The Important Topics We Didn’t Cover
1. Lexical Scoping
2. Method References
3. Method Handlers
4. Default Methods and Static methods in Interface
5. Streams in Java 8
6. Java 8 Date API
7. invokedynamic
8. Concurrency in lambda
9. Advanced Collections
10. Design and Architecture Principles
References:
❖ Special Thanks to Richard Warburton for “Java 8
lambdas”.
❖ “Implementing Lambda Expressions in Java” by Brian
Goetz.
❖ “Lambda Expressions in Java” by Simon Ritter.
❖ Oracle Java 8 Api Docs.
❖ Translation Of Lambda Expression by OpenJDK.(http:
//cr.openjdk.java.net/~briangoetz/lambda/lambda-
translation.html)
And many more like, DZone, StackOverflow etc.

Más contenido relacionado

La actualidad más candente

Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8Knoldus Inc.
 
The Dark Side Of Lambda Expressions in Java 8
The Dark Side Of Lambda Expressions in Java 8The Dark Side Of Lambda Expressions in Java 8
The Dark Side Of Lambda Expressions in Java 8Takipi
 
Lambda Expressions in Java 8
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8icarter09
 
java 8 new features
java 8 new features java 8 new features
java 8 new features Rohit Verma
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features OverviewSergii Stets
 
Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java langer4711
 
Functional Java 8 in everyday life
Functional Java 8 in everyday lifeFunctional Java 8 in everyday life
Functional Java 8 in everyday lifeAndrea Iacono
 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project LambdaRahman USTA
 

La actualidad más candente (20)

Java8
Java8Java8
Java8
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8
 
The Dark Side Of Lambda Expressions in Java 8
The Dark Side Of Lambda Expressions in Java 8The Dark Side Of Lambda Expressions in Java 8
The Dark Side Of Lambda Expressions in Java 8
 
Lambda Expressions in Java 8
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8
 
java 8 new features
java 8 new features java 8 new features
java 8 new features
 
Java 8 by example!
Java 8 by example!Java 8 by example!
Java 8 by example!
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features Overview
 
Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java
 
Java 8 Feature Preview
Java 8 Feature PreviewJava 8 Feature Preview
Java 8 Feature Preview
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
 
Java 8 Features
Java 8 FeaturesJava 8 Features
Java 8 Features
 
Java8 features
Java8 featuresJava8 features
Java8 features
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
 
Major Java 8 features
Major Java 8 featuresMajor Java 8 features
Major Java 8 features
 
Java 8 new features
Java 8 new featuresJava 8 new features
Java 8 new features
 
Functional Java 8 in everyday life
Functional Java 8 in everyday lifeFunctional Java 8 in everyday life
Functional Java 8 in everyday life
 
Java 8: the good parts!
Java 8: the good parts!Java 8: the good parts!
Java 8: the good parts!
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Streams in Java 8
Streams in Java 8Streams in Java 8
Streams in Java 8
 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project Lambda
 

Similar a Functional programming in java 8 by harmeet singh

Java 8 - An Overview
Java 8 - An OverviewJava 8 - An Overview
Java 8 - An OverviewIndrajit Das
 
Lambdas and-streams-s ritter-v3
Lambdas and-streams-s ritter-v3Lambdas and-streams-s ritter-v3
Lambdas and-streams-s ritter-v3Simon Ritter
 
Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...
Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...
Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...jaxLondonConference
 
Functional Programming In Jdk8
Functional Programming In Jdk8 Functional Programming In Jdk8
Functional Programming In Jdk8 Bansilal Haudakari
 
Eclipse Day India 2015 - Java 8 Overview
Eclipse Day India 2015 - Java 8 OverviewEclipse Day India 2015 - Java 8 Overview
Eclipse Day India 2015 - Java 8 OverviewEclipse Day India
 
New Features of JAVA SE8
New Features of JAVA SE8New Features of JAVA SE8
New Features of JAVA SE8Dinesh Pathak
 
Lambda Expressions Java 8 Features usage
Lambda Expressions  Java 8 Features usageLambda Expressions  Java 8 Features usage
Lambda Expressions Java 8 Features usageAsmaShaikh478737
 
Java 8 lambdas expressions
Java 8 lambdas expressionsJava 8 lambdas expressions
Java 8 lambdas expressionsLars Lemos
 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 itiAhmed mar3y
 
Functional Programming With Lambdas and Streams in JDK8
 Functional Programming With Lambdas and Streams in JDK8 Functional Programming With Lambdas and Streams in JDK8
Functional Programming With Lambdas and Streams in JDK8IndicThreads
 
java150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxjava150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxBruceLee275640
 
What's new in java 8
What's new in java 8What's new in java 8
What's new in java 8Dian Aditya
 

Similar a Functional programming in java 8 by harmeet singh (20)

Colloquium Report
Colloquium ReportColloquium Report
Colloquium Report
 
Java 8 - An Overview
Java 8 - An OverviewJava 8 - An Overview
Java 8 - An Overview
 
Insight into java 1.8, OOP VS FP
Insight into java 1.8, OOP VS FPInsight into java 1.8, OOP VS FP
Insight into java 1.8, OOP VS FP
 
Java 8-revealed
Java 8-revealedJava 8-revealed
Java 8-revealed
 
Lambdas
LambdasLambdas
Lambdas
 
Java 8
Java 8Java 8
Java 8
 
Lambdas and-streams-s ritter-v3
Lambdas and-streams-s ritter-v3Lambdas and-streams-s ritter-v3
Lambdas and-streams-s ritter-v3
 
Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...
Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...
Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...
 
Functional Programming In Jdk8
Functional Programming In Jdk8 Functional Programming In Jdk8
Functional Programming In Jdk8
 
Eclipse Day India 2015 - Java 8 Overview
Eclipse Day India 2015 - Java 8 OverviewEclipse Day India 2015 - Java 8 Overview
Eclipse Day India 2015 - Java 8 Overview
 
New Features of JAVA SE8
New Features of JAVA SE8New Features of JAVA SE8
New Features of JAVA SE8
 
Lambda Expressions Java 8 Features usage
Lambda Expressions  Java 8 Features usageLambda Expressions  Java 8 Features usage
Lambda Expressions Java 8 Features usage
 
Lambdas in Java 8
Lambdas in Java 8Lambdas in Java 8
Lambdas in Java 8
 
Java 8 lambdas expressions
Java 8 lambdas expressionsJava 8 lambdas expressions
Java 8 lambdas expressions
 
What`s New in Java 8
What`s New in Java 8What`s New in Java 8
What`s New in Java 8
 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 iti
 
Functional Programming With Lambdas and Streams in JDK8
 Functional Programming With Lambdas and Streams in JDK8 Functional Programming With Lambdas and Streams in JDK8
Functional Programming With Lambdas and Streams in JDK8
 
java150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxjava150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptx
 
Java 8 Overview
Java 8 OverviewJava 8 Overview
Java 8 Overview
 
What's new in java 8
What's new in java 8What's new in java 8
What's new in java 8
 

Último

Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 

Último (20)

Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 

Functional programming in java 8 by harmeet singh

  • 1. Functional Programming In JAVA By Harmeet Singh(Taara) (Java EE Developer) Email: harmeetsingh.0013@gmail.com Blog: http://harmeetsingh13.blogspot.in Skype: harmeetsingh0013 Contact: Via Email or Skype
  • 2. ➢ Introduction ➢ Functional Programming. ➢ Single Abstract Method(SAM). ➢ Functional Interface. ➢ Declare Lambda Expressions. ➢ Code Refactor Using Lambda Expression. ➢ Predefined Functional Interfaces in Java 8. ➢ User Defined Functional Interface in Java 8. ➢ Type Inference. ➢ Translation Of Lambda Expressions. ➢ Runtime Translation Strategies. ➢ Leftover: The Things We Didn’t Cover. Contents
  • 3. Acknowledgement ❖ Thanks To My Parents. ❖ Thanks To All Who Support Me or Not. ❖ Dedicated To My Teacher “Mr. Kapil Sakhuja”.
  • 4. Introduction In Java 8, the functional programming is the important evolution in Object Oriented Programming world of Java. Now, Java use lambdas, Simple Abstract Method (SAM) etc for allow functional programming in Object Oriented World. There are so many new features are added in Java 8 like Streams, Default methods etc. But Today’s we only discuss about “Functional Programming In Java”.
  • 5. What is Functional Programming ? Immutable Object: In Object Oriented and Functional Programming, An Immutable Object is an object whose state cannot be modified after it is created. Functional Programming: Functional Programming involves writing code that does not change state. One of the key feature of Functional Programming is the First- Class Functions.
  • 6. Single Abstract Method(SAM) Interfaces have one Abstract Method are called SAM. In Java there are lots of interfaces which only have one abstract method(by default interface have abstract method) like Runnable, Closeable etc. These Single Abstract Method(SAM) Interfaces are also called “Functional Interface”.
  • 7. Functional Interface Functional Interface: In Java 8, If Functional Interface have more than one methods, one is different and rest of the methods have same signature of Object class methods. These types of Interfaces also called Functional Interfaces like Comparator etc in Java. If interface have one abstract method and one or more than one Default and Static methods are also called Functional Interface.
  • 8. Declare Lambda Expression Syntax : lambda = ArgList “->” Body ArgList = Identifier && Body = Expression Examples: (int x, int y) -> { return x+y } (x, y) -? { return x+y } (x) -> { return x+1 } () -> { System.out.println(“Hello World”) }
  • 10. Predefined Functional Interfaces in Java 8 In Java 8, There are lots of Predefined Functional Interface, But today’s we only cover some important Functional interfaces are :-
  • 11. Predefined Functional Interfaces in Java 8 Predicate<T>: Represents a predicate (boolean-value- function) of one argument. Example:
  • 12. Predefined Functional Interfaces in Java 8 Consumer<T>: Represents an operation that accept a single input argument and returns no result. Example:
  • 13. Predefined Functional Interfaces in Java 8 Function<T, R>: Represents a function that accept a one argument and produces a result. Example:
  • 14. Predefined Functional Interfaces in Java 8 Supplier<T>: Represents a supplier of results Example:
  • 15. Predefined Functional Interfaces in Java 8 UnaryOperator<T>: Represents an operations on a single operands that produces a result of the same type as its operand. Example:
  • 16. Predefined Functional Interfaces in Java 8 BinaryOperator<T, T>: Represents an operations upon two operands of same type, producing a result of the same type as the operands. Example:
  • 17. User Defined Functional Interfaces In Java 8 IN Java 8, it is also possible to create our custom user define Functional Interface with the help of “@FunctionalInterface” annotation. Our Functional Interfaces also have default methods and static methods. @FunctionalInterface: @FunctionalInterface annotation indicates that the type declaration is intended to be a functional interface, as defined by Java Language Specification.
  • 18. User Defined Functional Interfaces In Java 8 Example:
  • 19. Type Inference Type Inference is not the new topic in Java. In Java 7 we create the Collections object with the help of Diamond Operator(<>) like : List<Integer> list = new ArrayList<>(); Under the hood of this code, Compiler use the “Type Inference” technique. In this compiler pick the type information from the left side of type declaration.
  • 20. Type Inference For Lambda expressions in Java 8, compiler use the same “Type Inference” technique with some improvements. Examples: Predicate<Integer> predicate = (x) -> x > 5; //code compile Predicate predicate = (x) -> x > 5; // Compile time error // Predicate is a raw type. References to generic type //Predicate<T> should be parameterized
  • 21. Translation Of Lambda Expression Translate the lambda expression to bytecode is major challenge for Java, because the important thing is to maintain backward compatibility in bytecode. There are so many challenges were faced for conversion like: 1. How to deal with Functional Interfaces? 2. For Lambdas use Inner classes? 3. Maintain Lambda information at runtime? etc.
  • 22. Translation Of Lambda Expression There are so many things are used and maintain for lambdas in JVM, But for JVM the lambdas are not a new, Because some languages are already use JVM for Runtime Environment that have “Lambda Expression” like Groovy, Scala, Clojure etc. Today we only discuss the brief steps for translate Lambda Expression after compilation.
  • 23. Translation Of Lambda Expression Followings are the Steps: ➔ Read “Lambda Expression” and desugars the lambda body into a method whose argument list and return type match that of “Lambda Expression”. Example : list.forEach( s -> { System.out.println(s); } ); //before compile static void lambda$1(String s) { //After compile System.out.println(s); }
  • 24. Translation Of Lambda Expression Followings are the Steps: ➔ At the point at which the “Lambda Expression” would be captured, it generates an “invokedynamic” CallSite like : list.forEach( s -> { System.out.println(s); } ); list.forEach( [lambda for lambda$1 as Block] );
  • 25. Translation Of Lambda Expression Followings are the Steps: ➔ This CallSite is called Lambda Factory for Given Lambda. ➔ The Dynamic Arguments to the lambda factory are the values captured from lexical scope. ➔ The Bootstrap Method for “Lambda Factory” is called “Lambda Metafactory”.
  • 26. Runtime Translation Strategies ➔ Generate Inner Classes Dynamically. ➔ Generate per-SAM wrapper class ◆ One per SAM type, not per lambda expression ◆ Use method handles for invocation. ◆ Use ClassValue to cache wrapper for SAM. ➔ Use Dynamic Proxies. ➔ Use MethodHandleProxies.asInterfaceInstance. ➔ Use VM private API to build object from scratch.
  • 27. Leftover: The Important Topics We Didn’t Cover 1. Lexical Scoping 2. Method References 3. Method Handlers 4. Default Methods and Static methods in Interface 5. Streams in Java 8 6. Java 8 Date API 7. invokedynamic 8. Concurrency in lambda 9. Advanced Collections 10. Design and Architecture Principles
  • 28. References: ❖ Special Thanks to Richard Warburton for “Java 8 lambdas”. ❖ “Implementing Lambda Expressions in Java” by Brian Goetz. ❖ “Lambda Expressions in Java” by Simon Ritter. ❖ Oracle Java 8 Api Docs. ❖ Translation Of Lambda Expression by OpenJDK.(http: //cr.openjdk.java.net/~briangoetz/lambda/lambda- translation.html) And many more like, DZone, StackOverflow etc.