SlideShare uma empresa Scribd logo
1 de 54
© Henri Tremblay 2015
Henri Tremblay
Senior Software Engineer
Terracotta, a Software AG company
Learn Java 8: Lambdas and Functional
Programming [TUT6198]
@henri_tremblay
2
Henri Tremblay
3
Henri Tremblay
4
Henri Tremblay
•  More or less made possible class mocking and proxying
•  Coined the term “partial mocking”
5
Henri Tremblay
•  More or less made possible class mocking and proxying
•  Coined the term “partial mocking”
6
7
Java < 8
8
Live Coding
9
8 minutes break (please do come back)
10
More Live Coding
11
Questions
12
You voting for me
13
Java 5
(2004)
14
JAVA 5 GAVE THE GENERIC
TYPES TO THE WORLD
(and also annotations, concurrent collections, enum types, for
each, static imports and so on and so on)
15
Type witness
MyClass.<List<String>> anyObject()
because you can’t
(List<String>) MyClass.anyObject()
16
Java 6
(2006, last from Sun)
17
JAVA 6 BROUGHT.. PRETTY
MUCH NOTHING
(a bunch of performance improvements under the hood, better xml
parsing and the first scripting api)
18
Java 7
(2011, first from Oracle)
19
JAVA 7 BROUGHT A LOT OF
SYNTACTIC SUGAR
(plus invokeDynamic, forkJoin, better file IO)
20
Switch for strings
switch(s) {
case "hello":
return "world";
case "bonjour":
return "le monde";
}
21
Diamond operator
List<String> list = new ArrayList<>();
22
Binary integer literals and underscores
int i = 0b1110001111;
int i = 1_000_000;
23
Multiple catches
try {
// ... do stuff
}
catch (IOException | SerializationException e) {
log.error("My error", e);
}
Instead of
try {
// ... do stuff
} catch (IOException e) {
log.error("My error", e);
} catch (SerializationException e) {
log.error("My error", e);
}
24
Auto Closeable
Before
InputStream in = new FileInputStream("allo.txt");
try {
// … do stuff
} finally {
try { in.close(); } catch(IOException e) {}
}
After
try(InputStream in = new FileInputStream("allo.txt")) {
// … do stuff
}
25
File IO API
List<String> lines =
Files.readAllLines(
Paths.get("path", "to", "my", "file.txt"));
// also: file watcher, symbolic links, file locks,
// copy … Look in java.nio.file
26
Java 8
(2014)
27
JAVA 8: LAMBDA!
(and also a new date API, default methods, metaspace, Nashorn,
JavaFX and CompletableFuture)
28
Base64 ;-)
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class Base64s {
public static void main(String[] args) {
final String text = "Base64 finally in Java 8!";
final String encoded = Base64
.getEncoder()
.encodeToString( text.getBytes( StandardCharsets.UTF_8 ) );
System.out.println( encoded );
final String decoded = new String(
Base64.getDecoder().decode( encoded ),
StandardCharsets.UTF_8 );
System.out.println( decoded );
}
}
29
Date / Time API
Core ideas:
  Immutable
  A time is a time, a date is a date. Not always both (like java.util.Date)
  Not everyone uses the same calendar (the same Chronology)
LocalDate, LocalTime, LocalDateTime à Local. No time zone
OffsetDateTime, OffsetTime à Time with an offset from
Greenwich
ZonedDateTime à LocalDateTime with a time zone
Duration, Period à Time span
Instant à Timestamp
Formatting à Easy and thread-safe formatting
30
Date / Time API (example)
LocalDateTime now = LocalDateTime.now();
String thatSpecialDay = now
.withDayOfMonth(1)
.atZone(ZoneId.of("Europe/Paris"))
.plus(Duration.ofDays(5))
.format(DateTimeFormatter.ISO_ZONED_DATE_TIME);
System.out.println(thatSpecialDay);
Output
2016-09-06T17:45:22.488+01:00[Europe/Paris]
31
Nashorn
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class Nashorn {
public static void main(String[] args) throws ScriptException {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName( "JavaScript" );
int i = (Integer) engine.eval( "function f() { return 1; }; f() + 1;");
System.out.println("Result: " + i);
}
}
Rhino Nashorn
Command
line: jjs
32
33
Lambda: 11th letter of the Greek alphabet
34
(also written as λ-calculus) is a formal system in
mathematical logic for expressing computation based
on function abstraction and application using variable
binding and substitution. It is a universal model of
computation that can be used to simulate any single-
taped Turing machine and was first introduced by
mathematician Alonzo Church in the 1930s as part of an
investigation into the foundations of mathematics.
Lambda calculus
35
This is a function:
This is a lambda:
Lambda calculus
36
c = sqrt(add(pow(a, 2), pow(b, 2)))
Functional programming
37
38
Lambda
// Classic
list.forEach(e -> System.out.println(e));
// Typed
list.forEach((String e) -> System.out.println(e));
// Multiline
list.forEach((String e) -> {
System.out.println(e);
});
// With closure
String greeting= "Hello ”;
list.forEach(e -> System.out.println(greeting + e));
39
Implicit final
List<String> list = new ArrayList<>();
String greeting = "Hello "; // no final required
list.forEach(s -> System.out.println(greeting + s));
list.forEach(new Consumer<String>() {
@Override public void accept(String s) {
System.out.println(greeting + s);
}
});
list.forEach(s -> greeting = “Hi”); // won’t compile
40
Everything is a lambda
public interface MyInterface {
int foo();
}
public void bar(MyInterface i) {
System.out.println(i.foo());
}
bar(() -> 4);
bar(new MyInterface() {
@Override public int foo() {
return 4;
}
});
JButton btn = new JButton();
btn.addActionListener(e -> {});
But it’s better to flag them
with
@FunctionalInterface
41
Method references
public static class Passenger {
public void inboard(Train train) {
System.out.println("Inboard " + train);
}
}
public static class Train {
public static Train create(Supplier< Train > supplier)
{
return supplier.get();
}
public static void paintBlue(Train train) {
System.out.println("Painted blue " + train);
}
public void repair() {
System.out.println( "Repaired " + this);
}
}
Train train = Train.create(Train::new); // constructor
List<Train> trains = Arrays.asList(train);
trains.forEach(Train::paintBlue); // static
method
trains.forEach(Train::repair); // instance
method
Passenger p = new Passenger();
trains.forEach(p::inboard); // instance
method taking this in param
trains.forEach(System.out::println); // useful!
42
Upside Down
public class MethodTest {
public class Foo {
static final String ERR_MESSAGE = "bad";
public void doIt() throws IllegalStateException {
throw new IllegalStateException(ERR_MESSAGE);
}
}
@Test
public void test() {
Foo foo = new Foo();
Throwable t = captureThrowable(foo::doIt);
assertThat(t)
.isInstanceOf(IllegalStateException.class)
.hasMessage(Foo.ERR_MESSAGE);
}
public static Throwable captureThrowable(Runnable r) {
Throwable result = null;
43
Streams
try(Stream<String> lines =
Files.lines(Paths.get("src/Streams.java"))) {
System.out.println(lines.findFirst());
}
44
Functional programming
List<String> list = new ArrayList<>();
int sum= list
.stream()
.filter(s -> s.startsWith("a"))
.mapToInt(String::length)
.sum();
List<Integer> length = list
.stream()
.map(String::length)
.collect(Collectors.toList());
45
Parallel
List<String> list = new ArrayList<>();
int sum = list
.parallelStream()
.filter(s -> s.startsWith("a"))
.mapToInt(String::length)
.sum();
Arrays.parallelSort(array);
46
Optional
try(Stream<String> lines =
Files.lines(Paths.get("src/Streams.java"))) {
System.out.println(lines.findFirst());
}
è  Optional[import java.io.IOException;]
Optional<String> findFirst();
Solution: lines.findFirst().get();
èimport java.io.IOException;
47
Interface default methods
public interface List<E> extends
Collection<E> {
default void replaceAll(UnaryOperator<E>
operator) {
// …
}
}
public interface A {
default void foo() { }
}
public interface B{
default void foo() { }
}
public class C implements A, B {} // forbidden
public class C implements A, B { // allowed
public void foo() { }
}
public static class D implements A, B { //
allowed
public void foo() {
A.super.foo();
}
}
48
Interface static methods
public interface IntStream {
static IntStream empty () {
return …;
}
}
IntStream stream = IntStream.empty ();
49
Break!
(8 minutes)
50
The End
51
Who has learned
something today?
?
52
Brian Goetz – State of the lambda
http://cr.openjdk.java.net/~briangoetz/lambda/lambda-state-
final.html
Ninja Squad – Lambda Kata
https://github.com/Ninja-Squad/ninjackaton-lambda
Maurice Naftalin’s lambda facts and books
http://www.lambdafaq.org/
  Mastering Lamdbas: Java Programming in a Multicore World
Links
53
54
Questions? http://montreal-jug.org
? http://easymock.org
http://objenesis.org
http:/ehcache.org
Henri Tremblay
http://blog.tremblay.pro
@henri_tremblay

Mais conteúdo relacionado

Mais procurados

Java Generics for Dummies
Java Generics for DummiesJava Generics for Dummies
Java Generics for Dummiesknutmork
 
Procedural Programming: It’s Back? It Never Went Away
Procedural Programming: It’s Back? It Never Went AwayProcedural Programming: It’s Back? It Never Went Away
Procedural Programming: It’s Back? It Never Went AwayKevlin Henney
 
Functional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting LambdasFunctional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting LambdasGanesh Samarthyam
 
Refactoring to Immutability
Refactoring to ImmutabilityRefactoring to Immutability
Refactoring to ImmutabilityKevlin Henney
 
Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8Ganesh Samarthyam
 
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions Ganesh Samarthyam
 
Lambda? You Keep Using that Letter
Lambda? You Keep Using that LetterLambda? You Keep Using that Letter
Lambda? You Keep Using that LetterKevlin Henney
 
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsQuark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsJohn De Goes
 
Porque aprender haskell me fez um programador python melhor?
Porque aprender haskell me fez um programador python melhor?Porque aprender haskell me fez um programador python melhor?
Porque aprender haskell me fez um programador python melhor?UFPA
 
Lambda and Stream Master class - part 1
Lambda and Stream Master class - part 1Lambda and Stream Master class - part 1
Lambda and Stream Master class - part 1José Paumard
 
Educational slides by venay magen
Educational slides by venay magenEducational slides by venay magen
Educational slides by venay magenvenaymagen19
 

Mais procurados (20)

Java Generics for Dummies
Java Generics for DummiesJava Generics for Dummies
Java Generics for Dummies
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Procedural Programming: It’s Back? It Never Went Away
Procedural Programming: It’s Back? It Never Went AwayProcedural Programming: It’s Back? It Never Went Away
Procedural Programming: It’s Back? It Never Went Away
 
Functional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting LambdasFunctional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting Lambdas
 
Refactoring to Immutability
Refactoring to ImmutabilityRefactoring to Immutability
Refactoring to Immutability
 
Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8
 
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 
Haskell
HaskellHaskell
Haskell
 
Lambda? You Keep Using that Letter
Lambda? You Keep Using that LetterLambda? You Keep Using that Letter
Lambda? You Keep Using that Letter
 
Java and j2ee_lab-manual
Java and j2ee_lab-manualJava and j2ee_lab-manual
Java and j2ee_lab-manual
 
ROP
ROPROP
ROP
 
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsQuark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
 
Stacks
StacksStacks
Stacks
 
Java generics
Java genericsJava generics
Java generics
 
Porque aprender haskell me fez um programador python melhor?
Porque aprender haskell me fez um programador python melhor?Porque aprender haskell me fez um programador python melhor?
Porque aprender haskell me fez um programador python melhor?
 
Anti patterns
Anti patternsAnti patterns
Anti patterns
 
Lambda and Stream Master class - part 1
Lambda and Stream Master class - part 1Lambda and Stream Master class - part 1
Lambda and Stream Master class - part 1
 
Stack, queue and hashing
Stack, queue and hashingStack, queue and hashing
Stack, queue and hashing
 
Educational slides by venay magen
Educational slides by venay magenEducational slides by venay magen
Educational slides by venay magen
 

Semelhante a JavaOne 2016 - Learn Lambda and functional programming

Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Ganesh Samarthyam
 
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...Akaks
 
New Functional Features of Java 8
New Functional Features of Java 8New Functional Features of Java 8
New Functional Features of Java 8franciscoortin
 
The... Wonderful? World of Lambdas
The... Wonderful? World of LambdasThe... Wonderful? World of Lambdas
The... Wonderful? World of LambdasEsther Lozano
 
New features and enhancement
New features and enhancementNew features and enhancement
New features and enhancementRakesh Madugula
 
Functional Programming in Java 8 - Lambdas and Streams
Functional Programming in Java 8 - Lambdas and StreamsFunctional Programming in Java 8 - Lambdas and Streams
Functional Programming in Java 8 - Lambdas and StreamsCodeOps Technologies LLP
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondMario Fusco
 
Modern Programming in Java 8 - Lambdas, Streams and Date Time API
Modern Programming in Java 8 - Lambdas, Streams and Date Time APIModern Programming in Java 8 - Lambdas, Streams and Date Time API
Modern Programming in Java 8 - Lambdas, Streams and Date Time APIGanesh Samarthyam
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8Martin Toshev
 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 itiAhmed mar3y
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeIan Robertson
 
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
 

Semelhante a JavaOne 2016 - Learn Lambda and functional programming (20)

Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams
 
Wien15 java8
Wien15 java8Wien15 java8
Wien15 java8
 
What is new in Java 8
What is new in Java 8What is new in Java 8
What is new in Java 8
 
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
 
Lambda Functions in Java 8
Lambda Functions in Java 8Lambda Functions in Java 8
Lambda Functions in Java 8
 
New Functional Features of Java 8
New Functional Features of Java 8New Functional Features of Java 8
New Functional Features of Java 8
 
The... Wonderful? World of Lambdas
The... Wonderful? World of LambdasThe... Wonderful? World of Lambdas
The... Wonderful? World of Lambdas
 
Major Java 8 features
Major Java 8 featuresMajor Java 8 features
Major Java 8 features
 
Java 8 Intro - Core Features
Java 8 Intro - Core FeaturesJava 8 Intro - Core Features
Java 8 Intro - Core Features
 
New features and enhancement
New features and enhancementNew features and enhancement
New features and enhancement
 
Functional Programming in Java 8 - Lambdas and Streams
Functional Programming in Java 8 - Lambdas and StreamsFunctional Programming in Java 8 - Lambdas and Streams
Functional Programming in Java 8 - Lambdas and Streams
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
 
Sailing with Java 8 Streams
Sailing with Java 8 StreamsSailing with Java 8 Streams
Sailing with Java 8 Streams
 
Modern Programming in Java 8 - Lambdas, Streams and Date Time API
Modern Programming in Java 8 - Lambdas, Streams and Date Time APIModern Programming in Java 8 - Lambdas, Streams and Date Time API
Modern Programming in Java 8 - Lambdas, Streams and Date Time API
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 iti
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive Code
 
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
 

Mais de Henri Tremblay

DevNexus 2020: Discover Modern Java
DevNexus 2020: Discover Modern JavaDevNexus 2020: Discover Modern Java
DevNexus 2020: Discover Modern JavaHenri Tremblay
 
OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?
OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?
OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?Henri Tremblay
 
Confoo 2018: Être pragmatique
Confoo 2018: Être pragmatiqueConfoo 2018: Être pragmatique
Confoo 2018: Être pragmatiqueHenri Tremblay
 
DevNexus 2018: Learn Java 8, lambdas and functional programming
DevNexus 2018: Learn Java 8, lambdas and functional programmingDevNexus 2018: Learn Java 8, lambdas and functional programming
DevNexus 2018: Learn Java 8, lambdas and functional programmingHenri Tremblay
 
Do you know your mock? - Madras JUG 20171028
Do you know your mock? - Madras JUG 20171028Do you know your mock? - Madras JUG 20171028
Do you know your mock? - Madras JUG 20171028Henri Tremblay
 
Be Pragmatic - JavaOne 2017
Be Pragmatic - JavaOne 2017Be Pragmatic - JavaOne 2017
Be Pragmatic - JavaOne 2017Henri Tremblay
 
Confoo 2016: Initiation aux tests de charge
Confoo 2016: Initiation aux tests de chargeConfoo 2016: Initiation aux tests de charge
Confoo 2016: Initiation aux tests de chargeHenri Tremblay
 
Réactif, parallèle, asynchrone. Pourquoi!
Réactif, parallèle, asynchrone. Pourquoi!Réactif, parallèle, asynchrone. Pourquoi!
Réactif, parallèle, asynchrone. Pourquoi!Henri Tremblay
 
Microbenchmarking with JMH
Microbenchmarking with JMHMicrobenchmarking with JMH
Microbenchmarking with JMHHenri Tremblay
 
Vivre en parallèle - Softshake 2013
Vivre en parallèle - Softshake 2013Vivre en parallèle - Softshake 2013
Vivre en parallèle - Softshake 2013Henri Tremblay
 
Performance perpétuelle (Devopsdays Paris 2013)
Performance perpétuelle (Devopsdays Paris 2013)Performance perpétuelle (Devopsdays Paris 2013)
Performance perpétuelle (Devopsdays Paris 2013)Henri Tremblay
 
DevoxxFR 2013: Lambda are coming. Meanwhile, are you sure we've mastered the ...
DevoxxFR 2013: Lambda are coming. Meanwhile, are you sure we've mastered the ...DevoxxFR 2013: Lambda are coming. Meanwhile, are you sure we've mastered the ...
DevoxxFR 2013: Lambda are coming. Meanwhile, are you sure we've mastered the ...Henri Tremblay
 

Mais de Henri Tremblay (13)

DevNexus 2020: Discover Modern Java
DevNexus 2020: Discover Modern JavaDevNexus 2020: Discover Modern Java
DevNexus 2020: Discover Modern Java
 
OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?
OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?
OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?
 
Confoo 2018: Être pragmatique
Confoo 2018: Être pragmatiqueConfoo 2018: Être pragmatique
Confoo 2018: Être pragmatique
 
DevNexus 2018: Learn Java 8, lambdas and functional programming
DevNexus 2018: Learn Java 8, lambdas and functional programmingDevNexus 2018: Learn Java 8, lambdas and functional programming
DevNexus 2018: Learn Java 8, lambdas and functional programming
 
Do you know your mock? - Madras JUG 20171028
Do you know your mock? - Madras JUG 20171028Do you know your mock? - Madras JUG 20171028
Do you know your mock? - Madras JUG 20171028
 
Be Pragmatic - JavaOne 2017
Be Pragmatic - JavaOne 2017Be Pragmatic - JavaOne 2017
Be Pragmatic - JavaOne 2017
 
Confoo 2016: Initiation aux tests de charge
Confoo 2016: Initiation aux tests de chargeConfoo 2016: Initiation aux tests de charge
Confoo 2016: Initiation aux tests de charge
 
Réactif, parallèle, asynchrone. Pourquoi!
Réactif, parallèle, asynchrone. Pourquoi!Réactif, parallèle, asynchrone. Pourquoi!
Réactif, parallèle, asynchrone. Pourquoi!
 
Perf university
Perf universityPerf university
Perf university
 
Microbenchmarking with JMH
Microbenchmarking with JMHMicrobenchmarking with JMH
Microbenchmarking with JMH
 
Vivre en parallèle - Softshake 2013
Vivre en parallèle - Softshake 2013Vivre en parallèle - Softshake 2013
Vivre en parallèle - Softshake 2013
 
Performance perpétuelle (Devopsdays Paris 2013)
Performance perpétuelle (Devopsdays Paris 2013)Performance perpétuelle (Devopsdays Paris 2013)
Performance perpétuelle (Devopsdays Paris 2013)
 
DevoxxFR 2013: Lambda are coming. Meanwhile, are you sure we've mastered the ...
DevoxxFR 2013: Lambda are coming. Meanwhile, are you sure we've mastered the ...DevoxxFR 2013: Lambda are coming. Meanwhile, are you sure we've mastered the ...
DevoxxFR 2013: Lambda are coming. Meanwhile, are you sure we've mastered the ...
 

Último

Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
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 WorkerThousandEyes
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...apidays
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
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.pdfsudhanshuwaghmare1
 
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 REVIEWERMadyBayot
 
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 2024The Digital Insurer
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
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].pdfOverkill Security
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
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 Processorsdebabhi2
 

Último (20)

Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
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
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
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
 
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
 
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
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
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
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
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
 

JavaOne 2016 - Learn Lambda and functional programming

  • 1. © Henri Tremblay 2015 Henri Tremblay Senior Software Engineer Terracotta, a Software AG company Learn Java 8: Lambdas and Functional Programming [TUT6198] @henri_tremblay
  • 4. 4 Henri Tremblay •  More or less made possible class mocking and proxying •  Coined the term “partial mocking”
  • 5. 5 Henri Tremblay •  More or less made possible class mocking and proxying •  Coined the term “partial mocking”
  • 6. 6
  • 9. 9 8 minutes break (please do come back)
  • 14. 14 JAVA 5 GAVE THE GENERIC TYPES TO THE WORLD (and also annotations, concurrent collections, enum types, for each, static imports and so on and so on)
  • 15. 15 Type witness MyClass.<List<String>> anyObject() because you can’t (List<String>) MyClass.anyObject()
  • 17. 17 JAVA 6 BROUGHT.. PRETTY MUCH NOTHING (a bunch of performance improvements under the hood, better xml parsing and the first scripting api)
  • 18. 18 Java 7 (2011, first from Oracle)
  • 19. 19 JAVA 7 BROUGHT A LOT OF SYNTACTIC SUGAR (plus invokeDynamic, forkJoin, better file IO)
  • 20. 20 Switch for strings switch(s) { case "hello": return "world"; case "bonjour": return "le monde"; }
  • 22. 22 Binary integer literals and underscores int i = 0b1110001111; int i = 1_000_000;
  • 23. 23 Multiple catches try { // ... do stuff } catch (IOException | SerializationException e) { log.error("My error", e); } Instead of try { // ... do stuff } catch (IOException e) { log.error("My error", e); } catch (SerializationException e) { log.error("My error", e); }
  • 24. 24 Auto Closeable Before InputStream in = new FileInputStream("allo.txt"); try { // … do stuff } finally { try { in.close(); } catch(IOException e) {} } After try(InputStream in = new FileInputStream("allo.txt")) { // … do stuff }
  • 25. 25 File IO API List<String> lines = Files.readAllLines( Paths.get("path", "to", "my", "file.txt")); // also: file watcher, symbolic links, file locks, // copy … Look in java.nio.file
  • 27. 27 JAVA 8: LAMBDA! (and also a new date API, default methods, metaspace, Nashorn, JavaFX and CompletableFuture)
  • 28. 28 Base64 ;-) import java.nio.charset.StandardCharsets; import java.util.Base64; public class Base64s { public static void main(String[] args) { final String text = "Base64 finally in Java 8!"; final String encoded = Base64 .getEncoder() .encodeToString( text.getBytes( StandardCharsets.UTF_8 ) ); System.out.println( encoded ); final String decoded = new String( Base64.getDecoder().decode( encoded ), StandardCharsets.UTF_8 ); System.out.println( decoded ); } }
  • 29. 29 Date / Time API Core ideas:   Immutable   A time is a time, a date is a date. Not always both (like java.util.Date)   Not everyone uses the same calendar (the same Chronology) LocalDate, LocalTime, LocalDateTime à Local. No time zone OffsetDateTime, OffsetTime à Time with an offset from Greenwich ZonedDateTime à LocalDateTime with a time zone Duration, Period à Time span Instant à Timestamp Formatting à Easy and thread-safe formatting
  • 30. 30 Date / Time API (example) LocalDateTime now = LocalDateTime.now(); String thatSpecialDay = now .withDayOfMonth(1) .atZone(ZoneId.of("Europe/Paris")) .plus(Duration.ofDays(5)) .format(DateTimeFormatter.ISO_ZONED_DATE_TIME); System.out.println(thatSpecialDay); Output 2016-09-06T17:45:22.488+01:00[Europe/Paris]
  • 31. 31 Nashorn import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; public class Nashorn { public static void main(String[] args) throws ScriptException { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName( "JavaScript" ); int i = (Integer) engine.eval( "function f() { return 1; }; f() + 1;"); System.out.println("Result: " + i); } } Rhino Nashorn Command line: jjs
  • 32. 32
  • 33. 33 Lambda: 11th letter of the Greek alphabet
  • 34. 34 (also written as λ-calculus) is a formal system in mathematical logic for expressing computation based on function abstraction and application using variable binding and substitution. It is a universal model of computation that can be used to simulate any single- taped Turing machine and was first introduced by mathematician Alonzo Church in the 1930s as part of an investigation into the foundations of mathematics. Lambda calculus
  • 35. 35 This is a function: This is a lambda: Lambda calculus
  • 36. 36 c = sqrt(add(pow(a, 2), pow(b, 2))) Functional programming
  • 37. 37
  • 38. 38 Lambda // Classic list.forEach(e -> System.out.println(e)); // Typed list.forEach((String e) -> System.out.println(e)); // Multiline list.forEach((String e) -> { System.out.println(e); }); // With closure String greeting= "Hello ”; list.forEach(e -> System.out.println(greeting + e));
  • 39. 39 Implicit final List<String> list = new ArrayList<>(); String greeting = "Hello "; // no final required list.forEach(s -> System.out.println(greeting + s)); list.forEach(new Consumer<String>() { @Override public void accept(String s) { System.out.println(greeting + s); } }); list.forEach(s -> greeting = “Hi”); // won’t compile
  • 40. 40 Everything is a lambda public interface MyInterface { int foo(); } public void bar(MyInterface i) { System.out.println(i.foo()); } bar(() -> 4); bar(new MyInterface() { @Override public int foo() { return 4; } }); JButton btn = new JButton(); btn.addActionListener(e -> {}); But it’s better to flag them with @FunctionalInterface
  • 41. 41 Method references public static class Passenger { public void inboard(Train train) { System.out.println("Inboard " + train); } } public static class Train { public static Train create(Supplier< Train > supplier) { return supplier.get(); } public static void paintBlue(Train train) { System.out.println("Painted blue " + train); } public void repair() { System.out.println( "Repaired " + this); } } Train train = Train.create(Train::new); // constructor List<Train> trains = Arrays.asList(train); trains.forEach(Train::paintBlue); // static method trains.forEach(Train::repair); // instance method Passenger p = new Passenger(); trains.forEach(p::inboard); // instance method taking this in param trains.forEach(System.out::println); // useful!
  • 42. 42 Upside Down public class MethodTest { public class Foo { static final String ERR_MESSAGE = "bad"; public void doIt() throws IllegalStateException { throw new IllegalStateException(ERR_MESSAGE); } } @Test public void test() { Foo foo = new Foo(); Throwable t = captureThrowable(foo::doIt); assertThat(t) .isInstanceOf(IllegalStateException.class) .hasMessage(Foo.ERR_MESSAGE); } public static Throwable captureThrowable(Runnable r) { Throwable result = null;
  • 44. 44 Functional programming List<String> list = new ArrayList<>(); int sum= list .stream() .filter(s -> s.startsWith("a")) .mapToInt(String::length) .sum(); List<Integer> length = list .stream() .map(String::length) .collect(Collectors.toList());
  • 45. 45 Parallel List<String> list = new ArrayList<>(); int sum = list .parallelStream() .filter(s -> s.startsWith("a")) .mapToInt(String::length) .sum(); Arrays.parallelSort(array);
  • 46. 46 Optional try(Stream<String> lines = Files.lines(Paths.get("src/Streams.java"))) { System.out.println(lines.findFirst()); } è  Optional[import java.io.IOException;] Optional<String> findFirst(); Solution: lines.findFirst().get(); èimport java.io.IOException;
  • 47. 47 Interface default methods public interface List<E> extends Collection<E> { default void replaceAll(UnaryOperator<E> operator) { // … } } public interface A { default void foo() { } } public interface B{ default void foo() { } } public class C implements A, B {} // forbidden public class C implements A, B { // allowed public void foo() { } } public static class D implements A, B { // allowed public void foo() { A.super.foo(); } }
  • 48. 48 Interface static methods public interface IntStream { static IntStream empty () { return …; } } IntStream stream = IntStream.empty ();
  • 52. 52 Brian Goetz – State of the lambda http://cr.openjdk.java.net/~briangoetz/lambda/lambda-state- final.html Ninja Squad – Lambda Kata https://github.com/Ninja-Squad/ninjackaton-lambda Maurice Naftalin’s lambda facts and books http://www.lambdafaq.org/   Mastering Lamdbas: Java Programming in a Multicore World Links
  • 53. 53