Presentation of Lambda in Java 8 for the Hanoi Java User Group on Thursday, April 16, 2015
http://www.meetup.com/Hanoi-Java-User-Group/events/220963110/
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
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
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
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