SlideShare a Scribd company logo
1 of 32
Design and Implementation
of Lambda Expressions in Java 8
Outline
1. What is the lambda calculus?
2. What is functional programming?
3. What are the benefits of functional
programming?
4. Functional programming in Java 8
5. Java 8 lambda expressions
6. Implementation of Java 8 lambda expressions
7. Streams
The Lambda Calculus
• The lambda calculus was introduced in the 1930s by
Alonzo Church as a mathematical system for defining
computable functions.
• The lambda calculus is equivalent in definitional
power to that of Turing machines.
• The lambda calculus serves as the computational
model underlying functional programming languages
such as Lisp, Haskell, and Ocaml.
• Features from the lambda calculus such as lambda
expressions have been incorporated into many
widely used programming languages like C++ and
now very recently Java 8.
What is the Lambda Calculus?
• The central concept in the lambda calculus is an
expression generated by the following grammar
which can denote a function definition, function
application, variable, or parenthesized expression:
expr → λ var . expr | expr expr | var | (expr)
• We can think of a lambda-calculus expression as a
program which when evaluated by beta-reductions
returns a result consisting of another lambda-
calculus expression.
Example of a Lambda Expression
• The lambda expression
λ x . (+ x 1) 2
represents the application of a function λ x . (+ x 1)
with a formal parameter x and a body + x 1 to the
argument 2. Notice that the function definition
λ x . (+ x 1) has no name; it is an anonymous
function.
• In Java 8, we would represent this function definition
by the Java 8 lambda expression x -> x + 1.
More Examples of Java 8 Lambdas
• A Java 8 lambda is basically a method in Java without a declaration
usually written as (parameters) -> { body }. Examples,
1. (int x, int y) -> { return x + y; }
2. x -> x * x
3. ( ) -> x
• A lambda can have zero or more parameters separated by commas
and their type can be explicitly declared or inferred from the
context.
• Parenthesis are not needed around a single parameter.
• ( ) is used to denote zero parameters.
• The body can contain zero or more statements.
• Braces are not needed around a single-statement body.
What is Functional Programming?
• A style of programming that treats computation as
the evaluation of mathematical functions
• Eliminates side effects
• Treats data as being immutable
• Expressions have referential transparency
• Functions can take functions as arguments and
return functions as results
• Prefers recursion over explicit for-loops
Why do Functional Programming?
• Allows us to write easier-to-understand, more
declarative, more concise programs than
imperative programming
• Allows us to focus on the problem rather than
the code
• Facilitates parallelism
Java 8
• Java 8 is the biggest change to Java since the
inception of the language
• Lambdas are the most important new addition
• Java is playing catch-up: most major
programming languages already have support
for lambda expressions
• A big challenge was to introduce lambdas
without requiring recompilation of existing
binaries
Benefits of Lambdas in Java 8
• Enabling functional programming
• Writing leaner more compact code
• Facilitating parallel programming
• Developing more generic, flexible and
reusable APIs
• Being able to pass behaviors as well as data to
functions
Java 8 Lambdas
• Syntax of Java 8 lambda expressions
• Functional interfaces
• Variable capture
• Method references
• Default methods
Example 1:
Print a list of integers with a lambda
List<Integer> intSeq = Arrays.asList(1,2,3);
intSeq.forEach(x -> System.out.println(x));
• x -> System.out.println(x) is a lambda expression that
defines an anonymous function with one parameter
named x of type Integer
Example 2:
A multiline lambda
List<Integer> intSeq = Arrays.asList(1,2,3);
intSeq.forEach(x -> {
x += 2;
System.out.println(x);
});
• Braces are needed to enclose a multiline body in a
lambda expression.
Example 3:
A lambda with a defined local variable
List<Integer> intSeq = Arrays.asList(1,2,3);
intSeq.forEach(x -> {
int y = x * 2;
System.out.println(y);
});
• Just as with ordinary functions, you can define local
variables inside the body of a lambda expression
Example 4:
A lambda with a declared parameter type
List<Integer> intSeq = Arrays.asList(1,2,3);
intSeq.forEach((Integer x -> {
x += 2;
System.out.println(x);
});
• You can, if you wish, specify the parameter type.
Implementation of Java 8 Lambdas
• The Java 8 compiler first converts a lambda expression
into a function
• It then calls the generated function
• For example, x -> System.out.println(x) could
be converted into a generated static function
public static void genName(Integer x) {
System.out.println(x);
}
• But what type should be generated for this function?
How should it be called? What class should it go in?
Functional Interfaces
• Design decision: Java 8 lambdas are assigned to functional
interfaces.
• A functional interface is a Java interface with exactly one
non-default method. E.g.,
public interface Consumer<T> {
void accept(T t);
}
• The package java.util.function defines many new
useful functional interfaces.
Assigning a Lambda to a Local Variable
public interface Consumer<T> {
void accept(T t);
}
void forEach(Consumer<Integer> action {
for (Integer i:items) {
action.accept(t);
}
}
List<Integer> intSeq = Arrrays.asList(1,2,3);
Consumer<Integer> cnsmr = x -> System.out.println(x);
intSeq.forEach(cnsmr);
Properties of the Generated Method
• The method generated from a Java 8 lambda
expression has the same signature as the
method in the functional interface
• The type is the same as that of the functional
interface to which the lambda expression is
assigned
• The lambda expression becomes the body of
the method in the interface
Variable Capture
• Lambdas can interact with variables defined
outside the body of the lambda
• Using these variables is called variable capture
Local Variable Capture Example
public class LVCExample {
public static void main(String[] args) {
List<Integer> intSeq = Arrays.asList(1,2,3);
int var = 10;
intSeq.forEach(x -> System.out.println(x + var));
}
}
• Note: local variables used inside the body of a lambda
must be final or effectively final
Static Variable Capture Example
public class SVCExample {
private static int var = 10;
public static void main(String[] args) {
List<Integer> intSeq = Arrays.asList(1,2,3);
intSeq.forEach(x -> System.out.println(x + var));
}
}
Method References
• Method references can be used to pass an
existing function in places where a lambda is
expected
• The signature of the referenced method needs
to match the signature of the functional
interface method
Summary of Method References
Method Reference
Type
Syntax Example
static ClassName::StaticMethodName String::valueOf
constructor ClassName::new ArrayList::new
specific object
instance
objectReference::MethodName x::toString
arbitrary object of a
given type
ClassName::InstanceMethodName Object::toString
Conciseness with Method References
We can rewrite the statement
intSeq.forEach(x -> System.out.println(x));
more concisely using a method reference
intSeq.forEach(System.out::println);
Default Methods
Java 8 uses lambda expressions and default
methods in conjunction with the Java collections
framework to achieve backward compatibility
with existing published interfaces
For a full discussion see Brian Goetz, Lambdas in
Java: A peek under the hood.
https://www.youtube.com/watch?v=MLksirK9nnE
Stream API
• The new java.util.stream package provides
utilities to support functional-style operations on
streams of values.
• A common way to obtain a stream is from a
collection:
Stream<T> stream = collection.stream();
• Streams can be sequential or parallel.
• Streams are useful for selecting values and
performing actions on the results.
Stream Operations
• An intermediate operation keeps a stream
open for further operations. Intermediate
operations are lazy.
• A terminal operation must be the final
operation on a stream. Once a terminal
operation is invoked, the stream is consumed
and is no longer usable.
Example Intermediate Operations
• filter excludes all elements that don’t
match a Predicate.
• map performs a one-to-one transformation of
elements using a Function.
A Stream Pipeline
A stream pipeline has three components:
1. A source such as a Collection, an array, a
generator function, or an IO channel;
2. Zero or more intermediate operations; and
3. A terminal operation
Stream Example
int sum = widgets.stream()
.filter(w -> w.getColor() == RED)
.mapToInt(w -> w.getWeight())
.sum();
Here, widgets is a Collection<Widget>. We create a stream of
Widget objects via Collection.stream(), filter it to produce a
stream containing only the red widgets, and then transform it into a
stream of int values representing the weight of each red widget.
Then this stream is summed to produce a total weight.
From Java Docs
Interface Stream<T>
Parting Example: Using lambdas and stream to
sum the squares of the elements on a list
List<Integer> list = Arrays.asList(1,2,3);
int sum = list.stream().map(x -> x*x).reduce((x,y) -> x + y).get();
System.out.println(sum);
• Here map(x -> x*x) squares each element and
then reduce((x,y) -> x + y) reduces all elements
into a single number
http://viralpatel.net/blogs/lambda-expressions-java-tutorial/

More Related Content

What's hot

Java 8 lambda expressions
Java 8 lambda expressionsJava 8 lambda expressions
Java 8 lambda expressionsLogan Chien
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentationVan Huong
 
java 8 new features
java 8 new features java 8 new features
java 8 new features Rohit Verma
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8LivePerson
 
Java Lambda Expressions.pptx
Java Lambda Expressions.pptxJava Lambda Expressions.pptx
Java Lambda Expressions.pptxSameerAhmed593310
 
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...Edureka!
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.David Gómez García
 
Whitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsWhitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsYura Nosenko
 
5. Destructuring | ES6 | Assignment
5. Destructuring | ES6 | Assignment 5. Destructuring | ES6 | Assignment
5. Destructuring | ES6 | Assignment pcnmtutorials
 
Java 8 - An Overview
Java 8 - An OverviewJava 8 - An Overview
Java 8 - An OverviewIndrajit Das
 
Java variable types
Java variable typesJava variable types
Java variable typesSoba Arjun
 
Lambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
Lambda Expressions in C# From Beginner To Expert - Jaliya UdagedaraLambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
Lambda Expressions in C# From Beginner To Expert - Jaliya UdagedaraJaliya Udagedara
 
Java 9/10/11 - What's new and why you should upgrade
Java 9/10/11 - What's new and why you should upgradeJava 9/10/11 - What's new and why you should upgrade
Java 9/10/11 - What's new and why you should upgradeSimone Bordet
 

What's hot (20)

Java8 features
Java8 featuresJava8 features
Java8 features
 
Java 8 lambda expressions
Java 8 lambda expressionsJava 8 lambda expressions
Java 8 lambda expressions
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
 
java 8 new features
java 8 new features java 8 new features
java 8 new features
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
 
Java Lambda Expressions.pptx
Java Lambda Expressions.pptxJava Lambda Expressions.pptx
Java Lambda Expressions.pptx
 
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.
 
Introduction to java 8 stream api
Introduction to java 8 stream apiIntroduction to java 8 stream api
Introduction to java 8 stream api
 
Whitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsWhitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applications
 
5. Destructuring | ES6 | Assignment
5. Destructuring | ES6 | Assignment 5. Destructuring | ES6 | Assignment
5. Destructuring | ES6 | Assignment
 
Java 8 - An Overview
Java 8 - An OverviewJava 8 - An Overview
Java 8 - An Overview
 
Java variable types
Java variable typesJava variable types
Java variable types
 
Optional in Java 8
Optional in Java 8Optional in Java 8
Optional in Java 8
 
Introduction to es6
Introduction to es6Introduction to es6
Introduction to es6
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Lambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
Lambda Expressions in C# From Beginner To Expert - Jaliya UdagedaraLambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
Lambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Java 9/10/11 - What's new and why you should upgrade
Java 9/10/11 - What's new and why you should upgradeJava 9/10/11 - What's new and why you should upgrade
Java 9/10/11 - What's new and why you should upgrade
 

Similar to Java 8 Lambda Expressions and Streams

Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streamsjessitron
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8Martin Toshev
 
Java8: what's new and what's hot
Java8: what's new and what's hotJava8: what's new and what's hot
Java8: what's new and what's hotSergii Maliarov
 
JDK8 Lambdas and Streams: Changing The Way You Think When Developing Java
JDK8 Lambdas and Streams: Changing The Way You Think When Developing JavaJDK8 Lambdas and Streams: Changing The Way You Think When Developing Java
JDK8 Lambdas and Streams: Changing The Way You Think When Developing JavaSimon Ritter
 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project LambdaRahman USTA
 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 itiAhmed mar3y
 
Learn ActionScript programming myassignmenthelp.net
Learn ActionScript programming myassignmenthelp.netLearn ActionScript programming myassignmenthelp.net
Learn ActionScript programming myassignmenthelp.netwww.myassignmenthelp.net
 
Programming with Python - Week 3
Programming with Python - Week 3Programming with Python - Week 3
Programming with Python - Week 3Ahmet Bulut
 
Fuel Up JavaScript with Functional Programming
Fuel Up JavaScript with Functional ProgrammingFuel Up JavaScript with Functional Programming
Fuel Up JavaScript with Functional ProgrammingShine Xavier
 
Functions in C++
Functions in C++Functions in C++
Functions in C++home
 
Automatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to InterfacesAutomatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to InterfacesRaffi Khatchadourian
 

Similar to Java 8 Lambda Expressions and Streams (20)

Java8
Java8Java8
Java8
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streams
 
Java 8 Intro - Core Features
Java 8 Intro - Core FeaturesJava 8 Intro - Core Features
Java 8 Intro - Core Features
 
Lambdas in Java 8
Lambdas in Java 8Lambdas in Java 8
Lambdas in Java 8
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
 
Java 8
Java 8Java 8
Java 8
 
Java 8
Java 8Java 8
Java 8
 
java8
java8java8
java8
 
Java8: what's new and what's hot
Java8: what's new and what's hotJava8: what's new and what's hot
Java8: what's new and what's hot
 
JDK8 Lambdas and Streams: Changing The Way You Think When Developing Java
JDK8 Lambdas and Streams: Changing The Way You Think When Developing JavaJDK8 Lambdas and Streams: Changing The Way You Think When Developing Java
JDK8 Lambdas and Streams: Changing The Way You Think When Developing Java
 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project Lambda
 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 iti
 
Learn ActionScript programming myassignmenthelp.net
Learn ActionScript programming myassignmenthelp.netLearn ActionScript programming myassignmenthelp.net
Learn ActionScript programming myassignmenthelp.net
 
Programming with Python - Week 3
Programming with Python - Week 3Programming with Python - Week 3
Programming with Python - Week 3
 
MatlabIntro (1).ppt
MatlabIntro (1).pptMatlabIntro (1).ppt
MatlabIntro (1).ppt
 
Fuel Up JavaScript with Functional Programming
Fuel Up JavaScript with Functional ProgrammingFuel Up JavaScript with Functional Programming
Fuel Up JavaScript with Functional Programming
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
 
Automatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to InterfacesAutomatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to Interfaces
 
Java 8 streams
Java 8 streams Java 8 streams
Java 8 streams
 

More from Manav Prasad (20)

Experience with mulesoft
Experience with mulesoftExperience with mulesoft
Experience with mulesoft
 
Mulesoftconnectors
MulesoftconnectorsMulesoftconnectors
Mulesoftconnectors
 
Mule and web services
Mule and web servicesMule and web services
Mule and web services
 
Mulesoft cloudhub
Mulesoft cloudhubMulesoft cloudhub
Mulesoft cloudhub
 
Perl tutorial
Perl tutorialPerl tutorial
Perl tutorial
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentation
 
Jpa
JpaJpa
Jpa
 
Spring introduction
Spring introductionSpring introduction
Spring introduction
 
Json
Json Json
Json
 
The spring framework
The spring frameworkThe spring framework
The spring framework
 
Rest introduction
Rest introductionRest introduction
Rest introduction
 
Exceptions in java
Exceptions in javaExceptions in java
Exceptions in java
 
Junit
JunitJunit
Junit
 
Xml parsers
Xml parsersXml parsers
Xml parsers
 
Xpath
XpathXpath
Xpath
 
Xslt
XsltXslt
Xslt
 
Xhtml
XhtmlXhtml
Xhtml
 
Css
CssCss
Css
 
Introduction to html5
Introduction to html5Introduction to html5
Introduction to html5
 
Ajax
AjaxAjax
Ajax
 

Recently uploaded

Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
Earthing details of Electrical Substation
Earthing details of Electrical SubstationEarthing details of Electrical Substation
Earthing details of Electrical Substationstephanwindworld
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvLewisJB
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
computer application and construction management
computer application and construction managementcomputer application and construction management
computer application and construction managementMariconPadriquez1
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfROCENODodongVILLACER
 
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgUnit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgsaravananr517913
 
lifi-technology with integration of IOT.pptx
lifi-technology with integration of IOT.pptxlifi-technology with integration of IOT.pptx
lifi-technology with integration of IOT.pptxsomshekarkn64
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catcherssdickerson1
 
Piping Basic stress analysis by engineering
Piping Basic stress analysis by engineeringPiping Basic stress analysis by engineering
Piping Basic stress analysis by engineeringJuanCarlosMorales19600
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)Dr SOUNDIRARAJ N
 
Class 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm SystemClass 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm Systemirfanmechengr
 
8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitter8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitterShivangiSharma879191
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEroselinkalist12
 
Solving The Right Triangles PowerPoint 2.ppt
Solving The Right Triangles PowerPoint 2.pptSolving The Right Triangles PowerPoint 2.ppt
Solving The Right Triangles PowerPoint 2.pptJasonTagapanGulla
 

Recently uploaded (20)

young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
Earthing details of Electrical Substation
Earthing details of Electrical SubstationEarthing details of Electrical Substation
Earthing details of Electrical Substation
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvv
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
computer application and construction management
computer application and construction managementcomputer application and construction management
computer application and construction management
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdf
 
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgUnit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
 
lifi-technology with integration of IOT.pptx
lifi-technology with integration of IOT.pptxlifi-technology with integration of IOT.pptx
lifi-technology with integration of IOT.pptx
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
 
Piping Basic stress analysis by engineering
Piping Basic stress analysis by engineeringPiping Basic stress analysis by engineering
Piping Basic stress analysis by engineering
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
 
Class 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm SystemClass 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm System
 
8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitter8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitter
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
 
Solving The Right Triangles PowerPoint 2.ppt
Solving The Right Triangles PowerPoint 2.pptSolving The Right Triangles PowerPoint 2.ppt
Solving The Right Triangles PowerPoint 2.ppt
 

Java 8 Lambda Expressions and Streams

  • 1. Design and Implementation of Lambda Expressions in Java 8
  • 2. Outline 1. What is the lambda calculus? 2. What is functional programming? 3. What are the benefits of functional programming? 4. Functional programming in Java 8 5. Java 8 lambda expressions 6. Implementation of Java 8 lambda expressions 7. Streams
  • 3. The Lambda Calculus • The lambda calculus was introduced in the 1930s by Alonzo Church as a mathematical system for defining computable functions. • The lambda calculus is equivalent in definitional power to that of Turing machines. • The lambda calculus serves as the computational model underlying functional programming languages such as Lisp, Haskell, and Ocaml. • Features from the lambda calculus such as lambda expressions have been incorporated into many widely used programming languages like C++ and now very recently Java 8.
  • 4. What is the Lambda Calculus? • The central concept in the lambda calculus is an expression generated by the following grammar which can denote a function definition, function application, variable, or parenthesized expression: expr → λ var . expr | expr expr | var | (expr) • We can think of a lambda-calculus expression as a program which when evaluated by beta-reductions returns a result consisting of another lambda- calculus expression.
  • 5. Example of a Lambda Expression • The lambda expression λ x . (+ x 1) 2 represents the application of a function λ x . (+ x 1) with a formal parameter x and a body + x 1 to the argument 2. Notice that the function definition λ x . (+ x 1) has no name; it is an anonymous function. • In Java 8, we would represent this function definition by the Java 8 lambda expression x -> x + 1.
  • 6. More Examples of Java 8 Lambdas • A Java 8 lambda is basically a method in Java without a declaration usually written as (parameters) -> { body }. Examples, 1. (int x, int y) -> { return x + y; } 2. x -> x * x 3. ( ) -> x • A lambda can have zero or more parameters separated by commas and their type can be explicitly declared or inferred from the context. • Parenthesis are not needed around a single parameter. • ( ) is used to denote zero parameters. • The body can contain zero or more statements. • Braces are not needed around a single-statement body.
  • 7. What is Functional Programming? • A style of programming that treats computation as the evaluation of mathematical functions • Eliminates side effects • Treats data as being immutable • Expressions have referential transparency • Functions can take functions as arguments and return functions as results • Prefers recursion over explicit for-loops
  • 8. Why do Functional Programming? • Allows us to write easier-to-understand, more declarative, more concise programs than imperative programming • Allows us to focus on the problem rather than the code • Facilitates parallelism
  • 9. Java 8 • Java 8 is the biggest change to Java since the inception of the language • Lambdas are the most important new addition • Java is playing catch-up: most major programming languages already have support for lambda expressions • A big challenge was to introduce lambdas without requiring recompilation of existing binaries
  • 10. Benefits of Lambdas in Java 8 • Enabling functional programming • Writing leaner more compact code • Facilitating parallel programming • Developing more generic, flexible and reusable APIs • Being able to pass behaviors as well as data to functions
  • 11. Java 8 Lambdas • Syntax of Java 8 lambda expressions • Functional interfaces • Variable capture • Method references • Default methods
  • 12. Example 1: Print a list of integers with a lambda List<Integer> intSeq = Arrays.asList(1,2,3); intSeq.forEach(x -> System.out.println(x)); • x -> System.out.println(x) is a lambda expression that defines an anonymous function with one parameter named x of type Integer
  • 13. Example 2: A multiline lambda List<Integer> intSeq = Arrays.asList(1,2,3); intSeq.forEach(x -> { x += 2; System.out.println(x); }); • Braces are needed to enclose a multiline body in a lambda expression.
  • 14. Example 3: A lambda with a defined local variable List<Integer> intSeq = Arrays.asList(1,2,3); intSeq.forEach(x -> { int y = x * 2; System.out.println(y); }); • Just as with ordinary functions, you can define local variables inside the body of a lambda expression
  • 15. Example 4: A lambda with a declared parameter type List<Integer> intSeq = Arrays.asList(1,2,3); intSeq.forEach((Integer x -> { x += 2; System.out.println(x); }); • You can, if you wish, specify the parameter type.
  • 16. Implementation of Java 8 Lambdas • The Java 8 compiler first converts a lambda expression into a function • It then calls the generated function • For example, x -> System.out.println(x) could be converted into a generated static function public static void genName(Integer x) { System.out.println(x); } • But what type should be generated for this function? How should it be called? What class should it go in?
  • 17. Functional Interfaces • Design decision: Java 8 lambdas are assigned to functional interfaces. • A functional interface is a Java interface with exactly one non-default method. E.g., public interface Consumer<T> { void accept(T t); } • The package java.util.function defines many new useful functional interfaces.
  • 18. Assigning a Lambda to a Local Variable public interface Consumer<T> { void accept(T t); } void forEach(Consumer<Integer> action { for (Integer i:items) { action.accept(t); } } List<Integer> intSeq = Arrrays.asList(1,2,3); Consumer<Integer> cnsmr = x -> System.out.println(x); intSeq.forEach(cnsmr);
  • 19. Properties of the Generated Method • The method generated from a Java 8 lambda expression has the same signature as the method in the functional interface • The type is the same as that of the functional interface to which the lambda expression is assigned • The lambda expression becomes the body of the method in the interface
  • 20. Variable Capture • Lambdas can interact with variables defined outside the body of the lambda • Using these variables is called variable capture
  • 21. Local Variable Capture Example public class LVCExample { public static void main(String[] args) { List<Integer> intSeq = Arrays.asList(1,2,3); int var = 10; intSeq.forEach(x -> System.out.println(x + var)); } } • Note: local variables used inside the body of a lambda must be final or effectively final
  • 22. Static Variable Capture Example public class SVCExample { private static int var = 10; public static void main(String[] args) { List<Integer> intSeq = Arrays.asList(1,2,3); intSeq.forEach(x -> System.out.println(x + var)); } }
  • 23. Method References • Method references can be used to pass an existing function in places where a lambda is expected • The signature of the referenced method needs to match the signature of the functional interface method
  • 24. Summary of Method References Method Reference Type Syntax Example static ClassName::StaticMethodName String::valueOf constructor ClassName::new ArrayList::new specific object instance objectReference::MethodName x::toString arbitrary object of a given type ClassName::InstanceMethodName Object::toString
  • 25. Conciseness with Method References We can rewrite the statement intSeq.forEach(x -> System.out.println(x)); more concisely using a method reference intSeq.forEach(System.out::println);
  • 26. Default Methods Java 8 uses lambda expressions and default methods in conjunction with the Java collections framework to achieve backward compatibility with existing published interfaces For a full discussion see Brian Goetz, Lambdas in Java: A peek under the hood. https://www.youtube.com/watch?v=MLksirK9nnE
  • 27. Stream API • The new java.util.stream package provides utilities to support functional-style operations on streams of values. • A common way to obtain a stream is from a collection: Stream<T> stream = collection.stream(); • Streams can be sequential or parallel. • Streams are useful for selecting values and performing actions on the results.
  • 28. Stream Operations • An intermediate operation keeps a stream open for further operations. Intermediate operations are lazy. • A terminal operation must be the final operation on a stream. Once a terminal operation is invoked, the stream is consumed and is no longer usable.
  • 29. Example Intermediate Operations • filter excludes all elements that don’t match a Predicate. • map performs a one-to-one transformation of elements using a Function.
  • 30. A Stream Pipeline A stream pipeline has three components: 1. A source such as a Collection, an array, a generator function, or an IO channel; 2. Zero or more intermediate operations; and 3. A terminal operation
  • 31. Stream Example int sum = widgets.stream() .filter(w -> w.getColor() == RED) .mapToInt(w -> w.getWeight()) .sum(); Here, widgets is a Collection<Widget>. We create a stream of Widget objects via Collection.stream(), filter it to produce a stream containing only the red widgets, and then transform it into a stream of int values representing the weight of each red widget. Then this stream is summed to produce a total weight. From Java Docs Interface Stream<T>
  • 32. Parting Example: Using lambdas and stream to sum the squares of the elements on a list List<Integer> list = Arrays.asList(1,2,3); int sum = list.stream().map(x -> x*x).reduce((x,y) -> x + y).get(); System.out.println(sum); • Here map(x -> x*x) squares each element and then reduce((x,y) -> x + y) reduces all elements into a single number http://viralpatel.net/blogs/lambda-expressions-java-tutorial/

Editor's Notes

  1. List<Integer> is a parameterized type, parameterized by the type argument <Integer> the Arrays.asList method returns a fixed-size list backed by an array; it can take “vararg” arguments forEach is a method that takes as input a function and calls the function for each value on the list Note the absence of type declarations in the lambda; the Java 8 compiler does type inference Java 8 is still statically typed Braces are not needed for single-line lambdas (but could be used if desired).
  2. Note: braces are needed to enclose a multiline lambda expression
  3. Just as with ordinary functions, you can define local variables inside the lambda expression
  4. You can, if you wish, specify the parameter type The compiler knows the type of intSeq is a list of Integers Since the compiler can do type inference, you don’t need to specify the type of x.
  5. What type should be generated for this function? How should it be called? What class should the translated lambda expression function be placed it? Should the generated method be a static or an instance method? The Java 8 designers spent a lot of time thinking about how to implement lambdas!
  6. Functional interfaces are a common idiom in Java code. Examples of existing JDK functional interfaces: Runnable, Comparable<T>, Callable<V>. Design decision: Java 8 lambdas should work with existing Java code without requiring recompilation.
  7. Here is an interface called Consumer with a single method called accept. The forEach method iterates through the items in the object Consumer and performs the action accept on each item. The lambda expression becomes the body of the function in the interface. The signature of the function is defined by the interface.
  8. Any interface with only one nondefault method is considered a functional interface by Java 8. So functional interfaces are Java 8’s secret sauce for backward compatibility.
  9. This lambda “captures” the variable var.