SlideShare a Scribd company logo
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 (20)

PDF
Lambda Expressions in Java
Erhan Bagdemir
 
PDF
Java 8 Lambda Expressions & Streams
NewCircle Training
 
ODP
Introduction to Java 8
Knoldus Inc.
 
PPTX
Java Lambda Expressions.pptx
SameerAhmed593310
 
PPTX
Introduction to java 8 stream api
Vladislav sidlyarevich
 
PDF
Generics
Ravi_Kant_Sahu
 
PPTX
Lambda Expressions in Java 8
icarter09
 
PDF
Java 8 Workshop
Mario Fusco
 
PDF
Introduction to Spring's Dependency Injection
Richard Paul
 
PDF
ES6 presentation
ritika1
 
PPTX
Functional programming with Java 8
LivePerson
 
PDF
Java 8 lambda expressions
Logan Chien
 
PPTX
Collections framework in java
yugandhar vadlamudi
 
PDF
Spring Boot
Jaran Flaath
 
PPT
Introduction to Javascript
Amit Tyagi
 
PPTX
Spring framework in depth
Vinay Kumar
 
PPT
Generics in java
suraj pandey
 
PDF
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
shaunthomas999
 
PDF
Python functions
Prof. Dr. K. Adisesha
 
Lambda Expressions in Java
Erhan Bagdemir
 
Java 8 Lambda Expressions & Streams
NewCircle Training
 
Introduction to Java 8
Knoldus Inc.
 
Java Lambda Expressions.pptx
SameerAhmed593310
 
Introduction to java 8 stream api
Vladislav sidlyarevich
 
Generics
Ravi_Kant_Sahu
 
Lambda Expressions in Java 8
icarter09
 
Java 8 Workshop
Mario Fusco
 
Introduction to Spring's Dependency Injection
Richard Paul
 
ES6 presentation
ritika1
 
Functional programming with Java 8
LivePerson
 
Java 8 lambda expressions
Logan Chien
 
Collections framework in java
yugandhar vadlamudi
 
Spring Boot
Jaran Flaath
 
Introduction to Javascript
Amit Tyagi
 
Spring framework in depth
Vinay Kumar
 
Generics in java
suraj pandey
 
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
shaunthomas999
 
Python functions
Prof. Dr. K. Adisesha
 

Similar to Java 8 lambda (20)

PDF
Lambdas in Java 8
Tobias Coetzee
 
PPTX
Week-1..................................
kmjanani05
 
PDF
Java 8
Sheeban Singaram
 
PDF
Java8
Felipe Mamud
 
PDF
Functional programming in java 8 by harmeet singh
Harmeet Singh(Taara)
 
PDF
Unit-3.pptx.pdf java api knowledge apiii
mpfbaa
 
PPTX
New features in jdk8 iti
Ahmed mar3y
 
PPTX
Simple Lambdas in java in oca 8.0 on feb
krishmf1
 
PPTX
Java Advanced Topic - Java Lambda Expressions.pptx
MuraliD32
 
PDF
Lambda Functions in Java 8
Ganesh Samarthyam
 
PPTX
Lambdas, Collections Framework, Stream API
Prabu U
 
PPTX
Lambda Expressions Java 8 Features usage
AsmaShaikh478737
 
PPT
Major Java 8 features
Sanjoy Kumar Roy
 
PPTX
Java 8
AbhimanuHandoo
 
PPTX
java150929145120-lva1-app6892 (2).pptx
BruceLee275640
 
PDF
Programming with Lambda Expressions in Java
langer4711
 
PDF
Presentation lambda calculus in java
Mahdi Cherif
 
PDF
Java 8-revealed
Hamed Hatami
 
PDF
Java8
Sunil Kumar
 
PDF
Modern Programming in Java 8 - Lambdas, Streams and Date Time API
Ganesh Samarthyam
 
Lambdas in Java 8
Tobias Coetzee
 
Week-1..................................
kmjanani05
 
Functional programming in java 8 by harmeet singh
Harmeet Singh(Taara)
 
Unit-3.pptx.pdf java api knowledge apiii
mpfbaa
 
New features in jdk8 iti
Ahmed mar3y
 
Simple Lambdas in java in oca 8.0 on feb
krishmf1
 
Java Advanced Topic - Java Lambda Expressions.pptx
MuraliD32
 
Lambda Functions in Java 8
Ganesh Samarthyam
 
Lambdas, Collections Framework, Stream API
Prabu U
 
Lambda Expressions Java 8 Features usage
AsmaShaikh478737
 
Major Java 8 features
Sanjoy Kumar Roy
 
java150929145120-lva1-app6892 (2).pptx
BruceLee275640
 
Programming with Lambda Expressions in Java
langer4711
 
Presentation lambda calculus in java
Mahdi Cherif
 
Java 8-revealed
Hamed Hatami
 
Modern Programming in Java 8 - Lambdas, Streams and Date Time API
Ganesh Samarthyam
 
Ad

More from Manav Prasad (20)

PPTX
Experience with mulesoft
Manav Prasad
 
PPTX
Mulesoftconnectors
Manav Prasad
 
PPT
Mule and web services
Manav Prasad
 
PPTX
Mulesoft cloudhub
Manav Prasad
 
PPT
Perl tutorial
Manav Prasad
 
PPT
Hibernate presentation
Manav Prasad
 
PPT
Jpa
Manav Prasad
 
PPT
Spring introduction
Manav Prasad
 
PPT
Json
Manav Prasad
 
PPT
The spring framework
Manav Prasad
 
PPT
Rest introduction
Manav Prasad
 
PPT
Exceptions in java
Manav Prasad
 
PPT
Junit
Manav Prasad
 
PPT
Xml parsers
Manav Prasad
 
PPT
Xpath
Manav Prasad
 
PPT
Xslt
Manav Prasad
 
PPT
Xhtml
Manav Prasad
 
PPT
Css
Manav Prasad
 
PPT
Introduction to html5
Manav Prasad
 
PPT
Ajax
Manav Prasad
 
Experience with mulesoft
Manav Prasad
 
Mulesoftconnectors
Manav Prasad
 
Mule and web services
Manav Prasad
 
Mulesoft cloudhub
Manav Prasad
 
Perl tutorial
Manav Prasad
 
Hibernate presentation
Manav Prasad
 
Spring introduction
Manav Prasad
 
The spring framework
Manav Prasad
 
Rest introduction
Manav Prasad
 
Exceptions in java
Manav Prasad
 
Xml parsers
Manav Prasad
 
Introduction to html5
Manav Prasad
 
Ad

Recently uploaded (20)

PPT
Footbinding.pptmnmkjkjkknmnnjkkkkkkkkkkkkkk
mamadoundiaye42742
 
PDF
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
PDF
MODULE-5 notes [BCG402-CG&V] PART-B.pdf
Alvas Institute of Engineering and technology, Moodabidri
 
PDF
SERVERLESS PERSONAL TO-DO LIST APPLICATION
anushaashraf20
 
PPTX
Lecture 1 Shell and Tube Heat exchanger-1.pptx
mailforillegalwork
 
PDF
Design Thinking basics for Engineers.pdf
CMR University
 
PPTX
澳洲电子毕业证澳大利亚圣母大学水印成绩单UNDA学生证网上可查学历
Taqyea
 
PDF
20ES1152 Programming for Problem Solving Lab Manual VRSEC.pdf
Ashutosh Satapathy
 
PDF
Data structures notes for unit 2 in computer science.pdf
sshubhamsingh265
 
PPTX
MODULE 03 - CLOUD COMPUTING AND SECURITY.pptx
Alvas Institute of Engineering and technology, Moodabidri
 
PPT
New_school_Engineering_presentation_011707.ppt
VinayKumar304579
 
PPTX
MODULE 05 - CLOUD COMPUTING AND SECURITY.pptx
Alvas Institute of Engineering and technology, Moodabidri
 
PDF
Pressure Measurement training for engineers and Technicians
AIESOLUTIONS
 
PPT
Testing and final inspection of a solar PV system
MuhammadSanni2
 
PPTX
Introduction to Internal Combustion Engines - Types, Working and Camparison.pptx
UtkarshPatil98
 
PDF
WD2(I)-RFQ-GW-1415_ Shifting and Filling of Sand in the Pond at the WD5 Area_...
ShahadathHossain23
 
PPTX
Worm gear strength and wear calculation as per standard VB Bhandari Databook.
shahveer210504
 
PDF
Digital water marking system project report
Kamal Acharya
 
PPTX
Numerical-Solutions-of-Ordinary-Differential-Equations.pptx
SAMUKTHAARM
 
PDF
3rd International Conference on Machine Learning and IoT (MLIoT 2025)
ClaraZara1
 
Footbinding.pptmnmkjkjkknmnnjkkkkkkkkkkkkkk
mamadoundiaye42742
 
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
MODULE-5 notes [BCG402-CG&V] PART-B.pdf
Alvas Institute of Engineering and technology, Moodabidri
 
SERVERLESS PERSONAL TO-DO LIST APPLICATION
anushaashraf20
 
Lecture 1 Shell and Tube Heat exchanger-1.pptx
mailforillegalwork
 
Design Thinking basics for Engineers.pdf
CMR University
 
澳洲电子毕业证澳大利亚圣母大学水印成绩单UNDA学生证网上可查学历
Taqyea
 
20ES1152 Programming for Problem Solving Lab Manual VRSEC.pdf
Ashutosh Satapathy
 
Data structures notes for unit 2 in computer science.pdf
sshubhamsingh265
 
MODULE 03 - CLOUD COMPUTING AND SECURITY.pptx
Alvas Institute of Engineering and technology, Moodabidri
 
New_school_Engineering_presentation_011707.ppt
VinayKumar304579
 
MODULE 05 - CLOUD COMPUTING AND SECURITY.pptx
Alvas Institute of Engineering and technology, Moodabidri
 
Pressure Measurement training for engineers and Technicians
AIESOLUTIONS
 
Testing and final inspection of a solar PV system
MuhammadSanni2
 
Introduction to Internal Combustion Engines - Types, Working and Camparison.pptx
UtkarshPatil98
 
WD2(I)-RFQ-GW-1415_ Shifting and Filling of Sand in the Pond at the WD5 Area_...
ShahadathHossain23
 
Worm gear strength and wear calculation as per standard VB Bhandari Databook.
shahveer210504
 
Digital water marking system project report
Kamal Acharya
 
Numerical-Solutions-of-Ordinary-Differential-Equations.pptx
SAMUKTHAARM
 
3rd International Conference on Machine Learning and IoT (MLIoT 2025)
ClaraZara1
 

Java 8 lambda

  • 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

  • #13: 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).
  • #14: Note: braces are needed to enclose a multiline lambda expression
  • #15: Just as with ordinary functions, you can define local variables inside the lambda expression
  • #16: 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.
  • #17: 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!
  • #18: 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.
  • #19: 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.
  • #20: 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.
  • #22: This lambda “captures” the variable var.