SlideShare a Scribd company logo
1 of 49
Download to read offline
Hanoi JUG - 2015
Java 8: Lambdas
Benoît de CHATEAUVIEUX - eXo
Hanoi JUG - 2015
Simple poll !
Who knows Java ?
Who knows Lambda ?
Who knows Functional Programming ?
Hanoi JUG - 2015
Why talking about Java 8 today ?
Java 7 End Of Public Updates =
April 2015
https://plumbr.eu/blog/java/java-version-statistics-2015-edition
Hanoi JUG - 2015
What’s new in Java 8 ?
Java 8 (March 18, 2014):
● JEP 126: Lambda & Stream
● JEP 174: Project Nashorn (JS in Java)
● JEP 104: Annotation on Java Types
● Unsigned Integer Arithmetic
● JEP 120: Repeating annotations
● JEP 150: Date and Time API
● JEP 178: Statically-linked JNI libraries
● JEP 153: Launch JavaFX applications
● JEP 122: Remove the permanent generation
JEP = JDK Enhancement Proposals
Hanoi JUG - 2015
Agenda
AGENDA
1. Basics
a. Lambda
b. Functional Interface
c. Default & Static method
2. Built-in functions
a. Built-in functions
b. Composing functions
3. Lambda: Advanced
a. Variable scoping
b. Effectively final
c. Method reference
4. Summary
Hanoi JUG - 2015
Lambda in Java
Lambda expressions is the single
largest upgrade to the programming
model ever - larger even than
generics.
This is the first time we have done a
carefully coordinated co-evolution of
the JVM, the language, and the
libraries all together – and the results
still feel like Java.
Mark Reinhold
“Chief Architect of the Java Platform”
https://blogs.oracle.com/java/entry/the_javaone_2013_technical_keynote
Hanoi JUG - 2015
So, what is lambda ?
Lambda comes from the Functional Programming:
- Lambda Calcul by Alonzo Church in 1936
- Lisp by John McCarthy in 1958
- ….
Functional Programming
1. Everything is a (mathematical) function
a. Pure functions (compute output from input → no side effect)
b. First-class and higher-order functions. i.e. function that
i. takes one or more functions as an input
ii. or outputs a function
2. Immutability
3. Recursion (no loop but functions that call themselves)
4. Lambda (anonymous functions)
Programming
Imperative
Declarative
Procedural (ex: Fortran, C)
Object Oriented (ex: Java, C++)
Logic (ex: Prolog)
Functional (ex: Haskell, Erlang)
Hanoi JUG - 2015
So, what is lambda ?
For us
Lambda == a piece of functionality
I will not detail
Functional Programming
in this presentation
Hey ! Opportunity for a future JUG meeting !
Any speaker ?
Hanoi JUG - 2015
Java 8: Lambdas
1. Basics
a. Lambda
b. Functional Interface
c. Default & Static method
2. Built-in functions
a. Built-in functions
b. Composing functions
3. Lambda: Advanced
a. Variable scoping
b. Effectively final
c. Method reference
4. Summary
Hanoi JUG - 2015
Syntax
Without lambda
new SomeInterface() {
@Override
public SomeType someMethod(OtherType args) {
… body ...
return result;
}
}
Lambda
(OtherType args) -> { … body … return result; }
Boilerplate code
Hanoi JUG - 2015
Example #1 : Runnable
Hanoi JUG - 2015
Example #2 : Comparator
Hanoi JUG - 2015
Hanoi JUG - 2015
Type inferencing
Types in argument list can be omitted.
Since there is only one method in the functional interface,
the compiler knows the expected types of the params
Basic lambda
(String firstName, String lastName) -> { return firstName + “ “ + lastName }
Lambda with type infering
(firstName, lastName) -> { return firstName + “ “ + lastName }
Hanoi JUG - 2015
Implied return value
For body, if expression is used instead of block, this
expression will be returned with no explicit “return” needed
If method is void, no value is returned
Basic lambda
(firstName, lastName) -> { return firstName + “ “ + lastName }
Lambda with implied return value
(firstName, lastName) -> { firstName + “ “ + lastName }
Hanoi JUG - 2015
Omitting parenthesis
If method takes a single parameter, parenthesis are
optional
Basic lambda
(firstName) -> { “First name: “ + firstName }
Lambda with implied return value
firstName -> { “First name: “ + firstName }
Hanoi JUG - 2015
Summary: lambda makes the code shorter
Java 7
taskList.execute(new Runnable() {
@Override
public void run() {
doSomething(arg);
}
});
Java 8
taskList.execute( () -> doSomething(arg) );
Hanoi JUG - 2015
Java 8: Lambdas
1. Basics
a. Lambda
b. Functional Interface
c. Default & Static method
2. Built-in functions
a. Built-in functions
b. Composing functions
3. Lambda: Advanced
a. Variable scoping
b. Effectively final
c. Method reference
4. Summary
Hanoi JUG - 2015
Definition
A functional interface is a Java
interface that lists only one method
declaration.
Previously, they were known as a Single Abstract Method type (SAM)
Hanoi JUG - 2015
@FunctionalInterface
Interfaces are same in Java 7 and Java 8
Implementations of interfaces are also same in Java 7 and Java 8
Code that call functional interface can use lambda or not
@FunctionalInterface is not required but expresses design intent
Functional interfaces can be verified at compile time
Hanoi JUG - 2015
Reminder: Definition
Hanoi JUG - 2015
Java 8: Lambdas
1. Basics
a. Lambda
b. Functional Interface
c. Default & Static method
2. Built-in functions
a. Built-in functions
b. Composing functions
3. Lambda: Advanced
a. Variable scoping
b. Effectively final
c. Method reference
4. Summary
Hanoi JUG - 2015
Default & Static methods
Functional interfaces have 1 single
abstract method (this is the method that
the lambda specifies)
But interfaces in Java 8 can have
default methods that
● have bodies
● are inherited
They also can have static methods
⇒ They are more like abstract classes
⇒ We now have multiple inheritance
of implementation in Java !
Hanoi JUG - 2015
Let’s code !
You can avoid writing your functional interface.
Java 8 has Built-in functions in java.util.
function package
So, let’s code…
If you want to code with lambda you have to
1. Write a functional interface (annotated or
not with @FunctionalInterface)
2. Write a code that call this functional
interface
Hanoi JUG - 2015
Java 8: Lambdas
AGENDA
1. Basics
a. Lambda
b. Functional Interface
c. Default & Static method
2. Built-in functions
a. Built-in functions
b. Composing functions
3. Lambda: Advanced
a. Variable scoping
b. Effectively final
c. Method reference
4. Summary
Hanoi JUG - 2015
Built-in functions
java.util.function package contains 43 general purpose functional interfaces.
4 families of functional interfaces
Those functions can be
● Simply Typed
● Generic
Function takes arguments and return something
Predicate take arguments and return a boolean
Consumer take arguments and return void
Supplier take no argument and return something
Hanoi JUG - 2015
Simply Typed Building Blocks
Functional interfaces are named according to arguments
and return value.
java.util.function package contains built-in functions for
simples types (Boolean, Double, Int, Long).
Some are
● Unary: one argument
● Binary: two arguments
ex: IntPredicate (int in, boolean out)
LongUnaryOperator(long in, long out)
DoubleBinaryOperator(two doubles in, double out)
Hanoi JUG - 2015
Generic Building Blocks
java.util.function package also contains generic built-in
functions:
● Function
○ Function<T,R> : unary function from T to R
○ BiFunction<T, U, R> : binary function from T and U to R
○ DoubleFunction<R> : unary function from double to R
○ ...
● Predicate
○ Predicate<T> : unary function from T to boolean
○ ...
● Consumer
○ Consumer<T> : unary function from T to void
○ ...
● Supplier
○ Supplier<T> : unary function from void to T
○ ...
Hanoi JUG - 2015
Example: Predicate
We’ll see in next presentation that getFirstMatchingActivity()
can be written more elegantly with Stream
Hanoi JUG - 2015
Java 8: Lambdas
1. Basics
a. Lambda
b. Functional Interface
c. Default & Static method
2. Built-in functions
a. Built-in functions
b. Composing functions
3. Lambda: Advanced
a. Variable scoping
b. Effectively final
c. Method reference
4. Summary
Hanoi JUG - 2015
Composing functions
Functional interfaces can be composed.
Some examples:
● Function
○ Function<V, R> compose(Function<? super V, ? extends T> before)
○ Function<T, V> andThen(Function<? super R, ? extends V> after)
○ Returns a composed Function that applies functions in sequence
● Predicate
○ Predicate<T> negate()
○ Predicate<T> and(Predicate<? super T> other)
○ Predicate<T> or(Predicate<? super T> other)
○ Compose predicates using boolean logic
● Consumer
○ Consumer<T> andThen(Consumer<? super T> after)
○ Returns a composed Consumer that performs operations in sequence
Hanoi JUG - 2015
Composing lambda: Example
Hanoi JUG - 2015
Custom methods that return Lambdas
Custom methods can also return lambda.
The method can use a parameter to generate the lambda.
Hanoi JUG - 2015
Java 8: Lambdas
AGENDA
1. Basics
a. Lambda
b. Functional Interface
c. Default & Static method
2. Built-in functions
a. Built-in functions
b. Composing functions
3. Lambda: Advanced
a. Variable scoping
b. Effectively final
c. Method reference
4. Summary
Hanoi JUG - 2015
Variable scoping
Let’s go back to our Runnable implementations.
Do you remember ?
Those implementations are strictly equivalent….
Hanoi JUG - 2015
Variable scoping
Well… not totally equivalent !
What happens if I introduce a local variable ?
Lambda does not introduce a new level of scoping
● Lambda cannot introduce new variables with the same name as variables
in method that creates the lambda
● “this” refers to the class the declare the lambda
Hanoi JUG - 2015
Java 8: Lambdas
1. Basics
a. Lambda
b. Functional Interface
c. Default & Static method
2. Built-in functions
a. Built-in functions
b. Composing functions
3. Lambda: Advanced
a. Variable scoping
b. Effectively final
c. Method reference
4. Summary
Hanoi JUG - 2015
Final vs Effectively final variables
● Lambda can only refer to local variable declared as final
● If a non-final local variable is never modified, the
compiler consider it as “effectively final”
Hanoi JUG - 2015
Final vs Effectively final variables
● This limitation does not apply to instance variables
Hanoi JUG - 2015
Java 8: Lambdas
1. Basics
a. Lambda
b. Functional Interface
c. Default & Static method
2. Built-in functions
a. Built-in functions
b. Composing functions
3. Lambda: Advanced
a. Variable scoping
b. Effectively final
c. Method reference
4. Summary
Hanoi JUG - 2015
Method reference
If the function we want to use already has a name, we don’t
have to write a lambda for it: we can just use the method
name:
● ClassName::staticMethodName
● variable::instanceMethodeName
● ClassName::new
Hanoi JUG - 2015
Java 8: Lambdas
AGENDA
1. Basics
a. Lambda
b. Functional Interface
c. Default & Static method
2. Built-in functions
a. Built-in functions
b. Composing functions
3. Lambda: Advanced
a. Variable scoping
b. Effectively final
c. Method reference
4. Summary
Hanoi JUG - 2015
So… when to use lambda ?
Use Case #1
Use it if you need a simple instance of a functional
interface and you do not need a constructor, a named
type, fields, or additional methods.
Benefits
⇒ more concise, readable and succinct code
⇒ compatible with old Java 7 interfaces
⇒ shipped with prebuilt functional interfaces
Hanoi JUG - 2015
So… when to use lambda ?
… but the syntax is not the most important
thing about lambda.
Hanoi JUG - 2015
So… when to use lambda ?
Use Case #2
Use it if you are encapsulating a single unit of behavior
that you want to pass to other code.
○ For example, you would use a lambda expression if you want a certain
action performed on each element of a collection, when a process is
completed, or when a process encounters an error.
Benefits
⇒ Start thinking in functions
⇒ avoid mutable states and thus locks
⇒ limit side-effects (and thus, bugs !)
⇒ design more composable and reusable API
Hanoi JUG - 2015
Paradigm shift
The really fundamental thing
about lambda expression
is the huge paradigm shift they imply.
… and learning a new language is relatively easy comparing to learning a new paradigm.
Hanoi JUG - 2015
Summary
Java is now poly-paradigm.
It’s getting functional.
Let’s go for it !
Hanoi JUG - 2015
Further readings
This presentation on Slideshare
● http://www.slideshare.net/benoitdechateauvieux/hanoi-jug-java-8-lambdas-
47013698
The code of this presentation
● https://github.com/benoitdechateauvieux/hanoi-jug-lambda
Further readings
● https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html
● http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/Lambda-
QuickStart/index.html
● http://www.slideshare.net/mariofusco/java-8-workshop
● http://www.beyondjava.net/blog/java-8-functional-programming-language/
● http://www.infoq.com/articles/How-Functional-is-Java-8
Hanoi JUG - 2015
Questions ?

More Related Content

What's hot

Functional programming in scala
Functional programming in scalaFunctional programming in scala
Functional programming in scala
Stratio
 
C++ OOP Implementation
C++ OOP ImplementationC++ OOP Implementation
C++ OOP Implementation
Fridz Felisco
 
Distributed Objects: CORBA/Java RMI
Distributed Objects: CORBA/Java RMIDistributed Objects: CORBA/Java RMI
Distributed Objects: CORBA/Java RMI
elliando dias
 

What's hot (20)

Introduction to Procedural Programming in C++
Introduction to Procedural Programming in C++Introduction to Procedural Programming in C++
Introduction to Procedural Programming in C++
 
Introduction to functional programming with java 8
Introduction to functional programming with java 8Introduction to functional programming with java 8
Introduction to functional programming with java 8
 
C++ ppt
C++ pptC++ ppt
C++ ppt
 
2.dynamic
2.dynamic2.dynamic
2.dynamic
 
Functional Programming With Python (EuroPython 2008)
Functional Programming With Python (EuroPython 2008)Functional Programming With Python (EuroPython 2008)
Functional Programming With Python (EuroPython 2008)
 
Functional programming in scala
Functional programming in scalaFunctional programming in scala
Functional programming in scala
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
 
Python Jump Start
Python Jump StartPython Jump Start
Python Jump Start
 
C++ to java
C++ to javaC++ to java
C++ to java
 
Basics of kotlin ASJ
Basics of kotlin ASJBasics of kotlin ASJ
Basics of kotlin ASJ
 
C by balaguruswami - e.balagurusamy
C   by balaguruswami - e.balagurusamyC   by balaguruswami - e.balagurusamy
C by balaguruswami - e.balagurusamy
 
C++ OOP Implementation
C++ OOP ImplementationC++ OOP Implementation
C++ OOP Implementation
 
Programming In C++
Programming In C++ Programming In C++
Programming In C++
 
Aaa ped-2- Python: Basics
Aaa ped-2- Python: BasicsAaa ped-2- Python: Basics
Aaa ped-2- Python: Basics
 
Oop l2
Oop l2Oop l2
Oop l2
 
Post-graduate course: Object technology: Implementation of object-oriented pr...
Post-graduate course: Object technology: Implementation of object-oriented pr...Post-graduate course: Object technology: Implementation of object-oriented pr...
Post-graduate course: Object technology: Implementation of object-oriented pr...
 
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
 
Distributed Objects: CORBA/Java RMI
Distributed Objects: CORBA/Java RMIDistributed Objects: CORBA/Java RMI
Distributed Objects: CORBA/Java RMI
 
Unit 1 cd
Unit 1 cdUnit 1 cd
Unit 1 cd
 
Why functional programming in C# & F#
Why functional programming in C# & F#Why functional programming in C# & F#
Why functional programming in C# & F#
 

Similar to Hanoi JUG: Java 8 & lambdas

Software Uni Conf October 2014
Software Uni Conf October 2014Software Uni Conf October 2014
Software Uni Conf October 2014
Nayden Gochev
 

Similar to Hanoi JUG: Java 8 & lambdas (20)

Software Uni Conf October 2014
Software Uni Conf October 2014Software Uni Conf October 2014
Software Uni Conf October 2014
 
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
 
Stream Api.pdf
Stream Api.pdfStream Api.pdf
Stream Api.pdf
 
java 8 new features
java 8 new features java 8 new features
java 8 new features
 
Lambda/Streams Hands-On Lab
Lambda/Streams Hands-On LabLambda/Streams Hands-On Lab
Lambda/Streams Hands-On Lab
 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project Lambda
 
Java modular extension for operator overloading
Java modular extension for operator overloadingJava modular extension for operator overloading
Java modular extension for operator overloading
 
Smart Migration to JDK 8
Smart Migration to JDK 8Smart Migration to JDK 8
Smart Migration to JDK 8
 
java150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxjava150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptx
 
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
 
Lambdas in Java 8
Lambdas in Java 8Lambdas in Java 8
Lambdas in Java 8
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
 
java8
java8java8
java8
 
Functional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singhFunctional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singh
 
Java 8
Java 8Java 8
Java 8
 
New Features of JAVA SE8
New Features of JAVA SE8New Features of JAVA SE8
New Features of JAVA SE8
 
Example Of Import Java
Example Of Import JavaExample Of Import Java
Example Of Import Java
 
Colloquium Report
Colloquium ReportColloquium Report
Colloquium Report
 
Functional programming
Functional programmingFunctional programming
Functional programming
 

Recently uploaded

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Recently uploaded (20)

Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 

Hanoi JUG: Java 8 & lambdas

  • 1. Hanoi JUG - 2015 Java 8: Lambdas Benoît de CHATEAUVIEUX - eXo
  • 2. Hanoi JUG - 2015 Simple poll ! Who knows Java ? Who knows Lambda ? Who knows Functional Programming ?
  • 3. Hanoi JUG - 2015 Why talking about Java 8 today ? Java 7 End Of Public Updates = April 2015 https://plumbr.eu/blog/java/java-version-statistics-2015-edition
  • 4. Hanoi JUG - 2015 What’s new in Java 8 ? Java 8 (March 18, 2014): ● JEP 126: Lambda & Stream ● JEP 174: Project Nashorn (JS in Java) ● JEP 104: Annotation on Java Types ● Unsigned Integer Arithmetic ● JEP 120: Repeating annotations ● JEP 150: Date and Time API ● JEP 178: Statically-linked JNI libraries ● JEP 153: Launch JavaFX applications ● JEP 122: Remove the permanent generation JEP = JDK Enhancement Proposals
  • 5. Hanoi JUG - 2015 Agenda AGENDA 1. Basics a. Lambda b. Functional Interface c. Default & Static method 2. Built-in functions a. Built-in functions b. Composing functions 3. Lambda: Advanced a. Variable scoping b. Effectively final c. Method reference 4. Summary
  • 6. Hanoi JUG - 2015 Lambda in Java Lambda expressions is the single largest upgrade to the programming model ever - larger even than generics. This is the first time we have done a carefully coordinated co-evolution of the JVM, the language, and the libraries all together – and the results still feel like Java. Mark Reinhold “Chief Architect of the Java Platform” https://blogs.oracle.com/java/entry/the_javaone_2013_technical_keynote
  • 7. Hanoi JUG - 2015 So, what is lambda ? Lambda comes from the Functional Programming: - Lambda Calcul by Alonzo Church in 1936 - Lisp by John McCarthy in 1958 - …. Functional Programming 1. Everything is a (mathematical) function a. Pure functions (compute output from input → no side effect) b. First-class and higher-order functions. i.e. function that i. takes one or more functions as an input ii. or outputs a function 2. Immutability 3. Recursion (no loop but functions that call themselves) 4. Lambda (anonymous functions) Programming Imperative Declarative Procedural (ex: Fortran, C) Object Oriented (ex: Java, C++) Logic (ex: Prolog) Functional (ex: Haskell, Erlang)
  • 8. Hanoi JUG - 2015 So, what is lambda ? For us Lambda == a piece of functionality I will not detail Functional Programming in this presentation Hey ! Opportunity for a future JUG meeting ! Any speaker ?
  • 9. Hanoi JUG - 2015 Java 8: Lambdas 1. Basics a. Lambda b. Functional Interface c. Default & Static method 2. Built-in functions a. Built-in functions b. Composing functions 3. Lambda: Advanced a. Variable scoping b. Effectively final c. Method reference 4. Summary
  • 10. Hanoi JUG - 2015 Syntax Without lambda new SomeInterface() { @Override public SomeType someMethod(OtherType args) { … body ... return result; } } Lambda (OtherType args) -> { … body … return result; } Boilerplate code
  • 11. Hanoi JUG - 2015 Example #1 : Runnable
  • 12. Hanoi JUG - 2015 Example #2 : Comparator
  • 13. Hanoi JUG - 2015
  • 14. Hanoi JUG - 2015 Type inferencing Types in argument list can be omitted. Since there is only one method in the functional interface, the compiler knows the expected types of the params Basic lambda (String firstName, String lastName) -> { return firstName + “ “ + lastName } Lambda with type infering (firstName, lastName) -> { return firstName + “ “ + lastName }
  • 15. Hanoi JUG - 2015 Implied return value For body, if expression is used instead of block, this expression will be returned with no explicit “return” needed If method is void, no value is returned Basic lambda (firstName, lastName) -> { return firstName + “ “ + lastName } Lambda with implied return value (firstName, lastName) -> { firstName + “ “ + lastName }
  • 16. Hanoi JUG - 2015 Omitting parenthesis If method takes a single parameter, parenthesis are optional Basic lambda (firstName) -> { “First name: “ + firstName } Lambda with implied return value firstName -> { “First name: “ + firstName }
  • 17. Hanoi JUG - 2015 Summary: lambda makes the code shorter Java 7 taskList.execute(new Runnable() { @Override public void run() { doSomething(arg); } }); Java 8 taskList.execute( () -> doSomething(arg) );
  • 18. Hanoi JUG - 2015 Java 8: Lambdas 1. Basics a. Lambda b. Functional Interface c. Default & Static method 2. Built-in functions a. Built-in functions b. Composing functions 3. Lambda: Advanced a. Variable scoping b. Effectively final c. Method reference 4. Summary
  • 19. Hanoi JUG - 2015 Definition A functional interface is a Java interface that lists only one method declaration. Previously, they were known as a Single Abstract Method type (SAM)
  • 20. Hanoi JUG - 2015 @FunctionalInterface Interfaces are same in Java 7 and Java 8 Implementations of interfaces are also same in Java 7 and Java 8 Code that call functional interface can use lambda or not @FunctionalInterface is not required but expresses design intent Functional interfaces can be verified at compile time
  • 21. Hanoi JUG - 2015 Reminder: Definition
  • 22. Hanoi JUG - 2015 Java 8: Lambdas 1. Basics a. Lambda b. Functional Interface c. Default & Static method 2. Built-in functions a. Built-in functions b. Composing functions 3. Lambda: Advanced a. Variable scoping b. Effectively final c. Method reference 4. Summary
  • 23. Hanoi JUG - 2015 Default & Static methods Functional interfaces have 1 single abstract method (this is the method that the lambda specifies) But interfaces in Java 8 can have default methods that ● have bodies ● are inherited They also can have static methods ⇒ They are more like abstract classes ⇒ We now have multiple inheritance of implementation in Java !
  • 24. Hanoi JUG - 2015 Let’s code ! You can avoid writing your functional interface. Java 8 has Built-in functions in java.util. function package So, let’s code… If you want to code with lambda you have to 1. Write a functional interface (annotated or not with @FunctionalInterface) 2. Write a code that call this functional interface
  • 25. Hanoi JUG - 2015 Java 8: Lambdas AGENDA 1. Basics a. Lambda b. Functional Interface c. Default & Static method 2. Built-in functions a. Built-in functions b. Composing functions 3. Lambda: Advanced a. Variable scoping b. Effectively final c. Method reference 4. Summary
  • 26. Hanoi JUG - 2015 Built-in functions java.util.function package contains 43 general purpose functional interfaces. 4 families of functional interfaces Those functions can be ● Simply Typed ● Generic Function takes arguments and return something Predicate take arguments and return a boolean Consumer take arguments and return void Supplier take no argument and return something
  • 27. Hanoi JUG - 2015 Simply Typed Building Blocks Functional interfaces are named according to arguments and return value. java.util.function package contains built-in functions for simples types (Boolean, Double, Int, Long). Some are ● Unary: one argument ● Binary: two arguments ex: IntPredicate (int in, boolean out) LongUnaryOperator(long in, long out) DoubleBinaryOperator(two doubles in, double out)
  • 28. Hanoi JUG - 2015 Generic Building Blocks java.util.function package also contains generic built-in functions: ● Function ○ Function<T,R> : unary function from T to R ○ BiFunction<T, U, R> : binary function from T and U to R ○ DoubleFunction<R> : unary function from double to R ○ ... ● Predicate ○ Predicate<T> : unary function from T to boolean ○ ... ● Consumer ○ Consumer<T> : unary function from T to void ○ ... ● Supplier ○ Supplier<T> : unary function from void to T ○ ...
  • 29. Hanoi JUG - 2015 Example: Predicate We’ll see in next presentation that getFirstMatchingActivity() can be written more elegantly with Stream
  • 30. Hanoi JUG - 2015 Java 8: Lambdas 1. Basics a. Lambda b. Functional Interface c. Default & Static method 2. Built-in functions a. Built-in functions b. Composing functions 3. Lambda: Advanced a. Variable scoping b. Effectively final c. Method reference 4. Summary
  • 31. Hanoi JUG - 2015 Composing functions Functional interfaces can be composed. Some examples: ● Function ○ Function<V, R> compose(Function<? super V, ? extends T> before) ○ Function<T, V> andThen(Function<? super R, ? extends V> after) ○ Returns a composed Function that applies functions in sequence ● Predicate ○ Predicate<T> negate() ○ Predicate<T> and(Predicate<? super T> other) ○ Predicate<T> or(Predicate<? super T> other) ○ Compose predicates using boolean logic ● Consumer ○ Consumer<T> andThen(Consumer<? super T> after) ○ Returns a composed Consumer that performs operations in sequence
  • 32. Hanoi JUG - 2015 Composing lambda: Example
  • 33. Hanoi JUG - 2015 Custom methods that return Lambdas Custom methods can also return lambda. The method can use a parameter to generate the lambda.
  • 34. Hanoi JUG - 2015 Java 8: Lambdas AGENDA 1. Basics a. Lambda b. Functional Interface c. Default & Static method 2. Built-in functions a. Built-in functions b. Composing functions 3. Lambda: Advanced a. Variable scoping b. Effectively final c. Method reference 4. Summary
  • 35. Hanoi JUG - 2015 Variable scoping Let’s go back to our Runnable implementations. Do you remember ? Those implementations are strictly equivalent….
  • 36. Hanoi JUG - 2015 Variable scoping Well… not totally equivalent ! What happens if I introduce a local variable ? Lambda does not introduce a new level of scoping ● Lambda cannot introduce new variables with the same name as variables in method that creates the lambda ● “this” refers to the class the declare the lambda
  • 37. Hanoi JUG - 2015 Java 8: Lambdas 1. Basics a. Lambda b. Functional Interface c. Default & Static method 2. Built-in functions a. Built-in functions b. Composing functions 3. Lambda: Advanced a. Variable scoping b. Effectively final c. Method reference 4. Summary
  • 38. Hanoi JUG - 2015 Final vs Effectively final variables ● Lambda can only refer to local variable declared as final ● If a non-final local variable is never modified, the compiler consider it as “effectively final”
  • 39. Hanoi JUG - 2015 Final vs Effectively final variables ● This limitation does not apply to instance variables
  • 40. Hanoi JUG - 2015 Java 8: Lambdas 1. Basics a. Lambda b. Functional Interface c. Default & Static method 2. Built-in functions a. Built-in functions b. Composing functions 3. Lambda: Advanced a. Variable scoping b. Effectively final c. Method reference 4. Summary
  • 41. Hanoi JUG - 2015 Method reference If the function we want to use already has a name, we don’t have to write a lambda for it: we can just use the method name: ● ClassName::staticMethodName ● variable::instanceMethodeName ● ClassName::new
  • 42. Hanoi JUG - 2015 Java 8: Lambdas AGENDA 1. Basics a. Lambda b. Functional Interface c. Default & Static method 2. Built-in functions a. Built-in functions b. Composing functions 3. Lambda: Advanced a. Variable scoping b. Effectively final c. Method reference 4. Summary
  • 43. Hanoi JUG - 2015 So… when to use lambda ? Use Case #1 Use it if you need a simple instance of a functional interface and you do not need a constructor, a named type, fields, or additional methods. Benefits ⇒ more concise, readable and succinct code ⇒ compatible with old Java 7 interfaces ⇒ shipped with prebuilt functional interfaces
  • 44. Hanoi JUG - 2015 So… when to use lambda ? … but the syntax is not the most important thing about lambda.
  • 45. Hanoi JUG - 2015 So… when to use lambda ? Use Case #2 Use it if you are encapsulating a single unit of behavior that you want to pass to other code. ○ For example, you would use a lambda expression if you want a certain action performed on each element of a collection, when a process is completed, or when a process encounters an error. Benefits ⇒ Start thinking in functions ⇒ avoid mutable states and thus locks ⇒ limit side-effects (and thus, bugs !) ⇒ design more composable and reusable API
  • 46. Hanoi JUG - 2015 Paradigm shift The really fundamental thing about lambda expression is the huge paradigm shift they imply. … and learning a new language is relatively easy comparing to learning a new paradigm.
  • 47. Hanoi JUG - 2015 Summary Java is now poly-paradigm. It’s getting functional. Let’s go for it !
  • 48. Hanoi JUG - 2015 Further readings This presentation on Slideshare ● http://www.slideshare.net/benoitdechateauvieux/hanoi-jug-java-8-lambdas- 47013698 The code of this presentation ● https://github.com/benoitdechateauvieux/hanoi-jug-lambda Further readings ● https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html ● http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/Lambda- QuickStart/index.html ● http://www.slideshare.net/mariofusco/java-8-workshop ● http://www.beyondjava.net/blog/java-8-functional-programming-language/ ● http://www.infoq.com/articles/How-Functional-is-Java-8
  • 49. Hanoi JUG - 2015 Questions ?