SlideShare uma empresa Scribd logo
1 de 71
© Henri Tremblay 2015
Henri Tremblay
Senior Software Engineer
Terracotta, a Software AG company
@henri_tremblay
Lambdas and generics survival guide
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
March 18 2014
7
Java 7 End of Life
8
September 2004
9
Lambda
return Tweet.TWEETS.stream()
.collect(Collectors
.partitioningBy(
t->t.containsHashTag("#lambda")));
10
Lambda = Fun with generics
Stream<Tweet> stream = Tweet.TWEETS.stream();
Predicate<Tweet> lambda = t -> t.containsHashTag("#lambda");
Collector<Tweet, ?, Map<Boolean, List<Tweet>>> collector =
Collectors.partitioningBy(lambda);
return stream.collect(collector);
11
What do I need to know?
Why
12
What do I need to know?
Why
Covariance
13
What do I need to know?
Why
Covariance
Capture
14
What do I need to know?
Why
Covariance
Capture
Inference
15
What do I need to know?
Why
Covariance
Capture
Inference
Erasure
16
What do I need to know?
Why Covariance
Capture Inference
Erasure Synthetic
17
Compile
18
Dreaded warnings
Type safety: The expression of type List needs
unchecked conversion to conform to List<String>
Type safety: Unchecked cast from
List<capture#1-of ?> to List<String>
19
Ostrich defense
@SuppressWarnings("unchecked")
20
Why
21
Rule #1
A code compiling
without warning should
never ever cause a
ClassCastException
22
Covariance
23
Arrays
Arrays are covariant:
Number n = Integer.MAX_VALUE;
Number[] list = new Integer[0];
Generics are not:
List<Number> l =
new ArrayList<Integer>(); // Illegal
24
Why not?
List<Integer> li = new ArrayList<Integer>();
List<Number> ln = li; // illegal
ln.add(new Float(3.1415));
int i = li.get(0); // ClassCastException
Would work if covariant And allow to break rule #1
25
Why for array?
Integer[] list = // ...
foo(list);
public void foo(Object[] o) {
// ...
}
26
Arrays and generics don’t mix well
Can’t have an array of generics
List<String>[] lsa = new List<String>[10];// illegal
27
Because
If it was allowed
List<String>[] lsa = new List<String>[10]; // illegal
Object[] oa = lsa; // OK (covariant)
oa[0] = new ArrayList<Integer>(); // OK
oa[0].add(42);
String s = lsa[0].get(0); // bad
28
Exception
List<?>[] l = new ArrayList<?>[3];
29
@SafeVarargs // Not actually safe!
static void m(List<String>... stringLists) {
Object[] array = stringLists;
List<Integer> tmpList = Arrays.asList(42);
array[0] = tmpList; // Semantically invalid, but compiles without warnings
String s = stringLists[0].get(0); // ClassCastException
}
@SafeVarargs (Java 7)
30
Capture
31
Capture usually is
Type
List<?> bar();
<T> IExpectationSetters<T> expect(T value);
void andReturn(T value); // Method of IExpectationSetters
expect(bar()).andReturn(new ArrayList<String>());
And you get
The method andReturn(List<capture#6-of ?>) in the type
IExpectationSetters<List<capture#6-of ?>> is not applicable for the arguments
(ArrayList<String>)
32
Detail
List<?> bar();
<T> IExpectationSetters<T> expect(T value);
void andReturn(T value);
expect(bar()).andReturn(new ArrayList<String>());
List<Capture#6> bar = bar();
IExpectationSetters<List<Capture#6>> es =
expect(bar());
es.andReturn(List<Capture#6> value);
33
Only solution
We need to cast
expect((List<String>) bar())
.andReturn(new ArrayList<String>());
But still a warning
Type safety: Unchecked cast from List<capture#6-of
?> to List<String>
Framework coder tip:
Try to never return a wildcard unless necessary
Tell to expect we want a
List<String>
34
Inference
35
Diamonds are a programmer best friend
List<String> l = new ArrayList<>();
36
How the compiler tells the type
<T> T anyObject(T t)
<T> T anyObject(Class<T> clazz)
The parameterDetermine the
return value
type
37
How the compiler tells the type
MyType var = <T> T anyObject()
Determine the return
type
The assigned
variable
38
But watch out with overloading
public void foo(String s)
public void foo(Object o)
foo(anyObject());
Can’t guess
the type
39
Trick #1
<T> T anyObject(Class<T> clazz)
Artificially give the type with a
dedicated parameter
Determine the return
value type
40
But how to pass a generic?
public void foo(String s)
public void foo(Object o)
foo(anyObject(List<String>.class));
Illegal
41
Some solutions
foo((String) anyObject());
foo((List<String>) anyObject()); // Warning
This would work
But still doesn’t work for
generics
42
Trick #2
So the only solution is called a “type witness”
foo(EasyMock.<List<String>> anyObject());
… which sadly doesn’t support static imports
foo(.<List<String>> anyObject()); // Illegal
43
Trick #2
So the only solution is called a “type witness”
foo(EasyMock.<List<String>> anyObject());
… which sadly doesn’t support static imports
foo(.<List<String>> anyObject()); // Illegal
44
Trick #2 applied to Lambda
return Tweet.TWEETS.stream()
.collect( Collectors.<Tweet, Boolean,
List<Tweet>, Map<Boolean, List<Tweet>>>
groupingBy(t->t.containsHashTag("#lambda"),
HashMap::new, ArrayList::new));
Return type: Map<Boolean, List<Tweet>>
45
Lambda = Inference
return Tweet.TWEETS.stream()
.collect(Collectors
.partitioningBy(
t->t.containsHashTag("#lambda"));
46
How did it do it?
Tweet.TWEETS.stream()
List<Tweet> list = Tweet.TWEETS;
Stream<Tweet> stream = list.stream();
47
How did it do it?
Stream<Tweet> stream = list.stream();
R result = stream.collect(Collector<? super T, ?, R> collector);
R result = stream.collect(Collector<? super Tweet, ?, R>
collector);
48
How did it do it?
stream.collect(Collector<? super Tweet, ?, R> collector);
Collector<T, ?, Map<Boolean, List<T>>> collector =
Collectors.partitioningBy(Predicate<? super T> predicate);
Collector<Tweet, ?, Map<Boolean, List<Tweet>>> collector =
Collectors.partitioningBy(Predicate<? super Tweet> predicate);
49
We now know that
So the best t can be is a Tweet
How did it do it?
Predicate<? super Tweet> lambda = t -> t.containsHashTag("#lambda");
Predicate<? super Tweet> lambda = (Tweet t) -> t.containsHashTag("#lambda");
50
Trick #3: Lambda inference
Object o = (Runnable) () -> {
System.out.println("hi");
};
Collections.sort(strings,
(String a, String b) -> a.compareTo(b));
51
Erasure
52
Erasure…
public void foo() {
List<String> l = new ArrayList<String>();
for (String s : l) {
System.out.println(s);
}
}
No type
public void foo() {
List l = new ArrayList();
for (String s : l) {
System.out.println(s);
}
}
Compilation
53
… or not erasure
public class A extends ArrayList<String> {}
public static void main(final String[] args) {
ParameterizedType type = (ParameterizedType)
A.class.getGenericSuperclass();
System.out.println(
type.getActualTypeArguments()[0]);
}
 prints class java.lang.String
54
Type class
java.lang.reflect.Type
• GenericArrayType
• ParameterizedType
• TypeVariable
• WildcardType
• Implemented by Class
java.lang.reflect.GenericDeclaration
Implemented by Class, Method, Constructor
New powers
unleashed!
55
Useful!
class A {}
abstract class BaseDao<T> {
public T load(final long id) {
// …
}
}
class ADao extends BaseDao<A> {}
56
Useful!
@SuppressWarnings("unchecked")
public T load(final long id) {
ParameterizedType type =
(ParameterizedType) getClass()
.getGenericSuperclass();
Type actualType = type.getActualTypeArguments()[0];
return em.find((Class<T>) actualType, (Long) id);
}
ADao
A
BaseDao<A>
Unsafe cast
57
Synthetic methods
58
Everything seems normal…
class A<T> {
abstract void set(T value);
}
class B extends A<String> {
String value;
@Override
void set(final String value) {
this.value = value;
}
}
59
But is not
class B extends A<String> {
void set(String value) {
this.value = value;
}
volatile void set(Object o){
set((String)o);
}
}
60
Example
A a = new B();
a.set(new Object());
But at runtime:
java.lang.ClassCastException
Raw type warning Perfectly compiling
61
The actual problem being
B.class.getDeclaredMethods()
volatile void set(java.lang.Object)
void B.set(java.lang.String)
This
Returns that
And gives you no way to find out
which method is bridged
62
What about lambdas?
public class A {
public static void main(String[] args) {
Method[] methods = A.class.getDeclaredMethods();
Arrays.stream(methods).forEach(m ->
System.out.println(m + " "
+ m.isBridge() + " " + m.isSynthetic()));
}
}
63
What about lambdas?
public class A {
public static void main(String[] args) {
Method[] methods = A.class.getDeclaredMethods();
Arrays.stream(methods).forEach(m ->
System.out.println(m + " "
+ m.isBridge() + " " + m.isSynthetic()));
}
}
Prints this
public static void A.main(java.lang.String[]) false false
private static void A.lambda$0(java.lang.reflect.Method) false true
64
Clean Code Bonus!
65
What’s wrong?
public static Set<Tweet> containing(String hashtag) {
return Tweet.TWEETS.stream()
.filter(t -> t.hasHashtag(hashtag))
.collect(Collectors.toSet());
}
66
What’s wrong?
public static Stream<Tweet> containing(String hashtag)
{
return Tweet.TWEETS.stream()
.filter(t -> t.hasHashtag(hashtag));
}
Return a Stream whenever you can
67
What’s wrong?
Tweet.TWEETS
.stream()
.filter(t -> t.hasHashtag("#lambda"))
.sorted(Comparator.comparing(Tweet::getSender)
.thenComparing(Tweet::getTimestamp))
.forEachOrdered(System.out::println);
}
68
What’s wrong?
public static void main(String[] args) {
getForHashtag("#lambda”).forEachOrdered(System.out::println);
}
private static Stream<Tweet> getForHashtag(String hashtag) {
return Tweet.TWEETS.stream()
.filter(hasHashtagPredicate(hashtag))
.sorted(bySenderThenTimestamp());
}
private static Predicate<Tweet> hasHashtagPredicate(String hashtag) {
return t -> t.hasHashtag(hashtag);
}
private static Comparator<Tweet> bySenderThenTimestamp() {
return Comparator.comparing(Tweet::getSender).thenComparing(Tweet::getTimestamp);
}
Refactor your one-liner
69
Who has learned
something today?
?
70
Useful links
Ninja Squad – Nice lambda dojo (in French)
• http://lambda.ninjackaton.ninja-squad.com/
Brian Goetz - Description of inference types on lambda
• http://cr.openjdk.java.net/~briangoetz/lambda/lambda-state-final.html
• http://www.slideshare.net/jaxlondon2012/lambda-a-peek-under-the-hood-brian-goetz
Angelika Langer - Everything on generics
• http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html
Maurice Naftalin – Facts and books
• http://www.lambdafaq.org/
• Java Generics and Collections: Speed Up the Java Development Process
• Mastering Lambdas: Java Programming in a Multicore World
71
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

Important java programs(collection+file)
Important java programs(collection+file)Important java programs(collection+file)
Important java programs(collection+file)Alok Kumar
 
Scala for Java Developers - Intro
Scala for Java Developers - IntroScala for Java Developers - Intro
Scala for Java Developers - IntroDavid Copeland
 
Functional Algebra: Monoids Applied
Functional Algebra: Monoids AppliedFunctional Algebra: Monoids Applied
Functional Algebra: Monoids AppliedSusan Potter
 
Programming Java - Lection 07 - Puzzlers - Lavrentyev Fedor
Programming Java - Lection 07 - Puzzlers - Lavrentyev FedorProgramming Java - Lection 07 - Puzzlers - Lavrentyev Fedor
Programming Java - Lection 07 - Puzzlers - Lavrentyev FedorFedor Lavrentyev
 
DevNation'15 - Using Lambda Expressions to Query a Datastore
DevNation'15 - Using Lambda Expressions to Query a DatastoreDevNation'15 - Using Lambda Expressions to Query a Datastore
DevNation'15 - Using Lambda Expressions to Query a DatastoreXavier Coulon
 
Intro to Functional Programming in Scala
Intro to Functional Programming in ScalaIntro to Functional Programming in Scala
Intro to Functional Programming in ScalaShai Yallin
 
Scala introduction
Scala introductionScala introduction
Scala introductionvito jeng
 
Fun never stops. introduction to haskell programming language
Fun never stops. introduction to haskell programming languageFun never stops. introduction to haskell programming language
Fun never stops. introduction to haskell programming languagePawel Szulc
 
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
 
Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Nishan Barot
 
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
 
Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldBTI360
 
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
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeGanesh Samarthyam
 

Mais procurados (20)

Java and j2ee_lab-manual
Java and j2ee_lab-manualJava and j2ee_lab-manual
Java and j2ee_lab-manual
 
Java programs
Java programsJava programs
Java programs
 
Important java programs(collection+file)
Important java programs(collection+file)Important java programs(collection+file)
Important java programs(collection+file)
 
Scala for Java Developers - Intro
Scala for Java Developers - IntroScala for Java Developers - Intro
Scala for Java Developers - Intro
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Functional Algebra: Monoids Applied
Functional Algebra: Monoids AppliedFunctional Algebra: Monoids Applied
Functional Algebra: Monoids Applied
 
Programming Java - Lection 07 - Puzzlers - Lavrentyev Fedor
Programming Java - Lection 07 - Puzzlers - Lavrentyev FedorProgramming Java - Lection 07 - Puzzlers - Lavrentyev Fedor
Programming Java - Lection 07 - Puzzlers - Lavrentyev Fedor
 
DevNation'15 - Using Lambda Expressions to Query a Datastore
DevNation'15 - Using Lambda Expressions to Query a DatastoreDevNation'15 - Using Lambda Expressions to Query a Datastore
DevNation'15 - Using Lambda Expressions to Query a Datastore
 
Intro to Functional Programming in Scala
Intro to Functional Programming in ScalaIntro to Functional Programming in Scala
Intro to Functional Programming in Scala
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Fun never stops. introduction to haskell programming language
Fun never stops. introduction to haskell programming languageFun never stops. introduction to haskell programming language
Fun never stops. introduction to haskell programming language
 
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
 
Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.
 
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
 
Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 World
 
Scala - brief intro
Scala - brief introScala - brief intro
Scala - brief intro
 
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
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean Code
 

Destaque

Practical tipsmakemobilefaster oscon2016
Practical tipsmakemobilefaster oscon2016Practical tipsmakemobilefaster oscon2016
Practical tipsmakemobilefaster oscon2016Doris Chen
 
Java Puzzlers NG S02: Down the Rabbit Hole as presented at DevNexus 2017
Java Puzzlers NG S02: Down the Rabbit Hole as presented at DevNexus 2017Java Puzzlers NG S02: Down the Rabbit Hole as presented at DevNexus 2017
Java Puzzlers NG S02: Down the Rabbit Hole as presented at DevNexus 2017Baruch Sadogursky
 
Developing Android applications with Ceylon
Developing Android applications with Ceylon Developing Android applications with Ceylon
Developing Android applications with Ceylon Enrique Zamudio López
 
DevOps @Scale (Greek Tragedy in 3 Acts) as it was presented at DevNexus 2017
DevOps @Scale (Greek Tragedy in 3 Acts) as it was presented at DevNexus 2017DevOps @Scale (Greek Tragedy in 3 Acts) as it was presented at DevNexus 2017
DevOps @Scale (Greek Tragedy in 3 Acts) as it was presented at DevNexus 2017Baruch Sadogursky
 
Agile Metrics : Velocity is NOT the Goal - NDC Oslo 2014
Agile Metrics : Velocity is NOT the Goal - NDC Oslo 2014Agile Metrics : Velocity is NOT the Goal - NDC Oslo 2014
Agile Metrics : Velocity is NOT the Goal - NDC Oslo 2014Doc Norton
 
Post-Modern CSS: Start learning CSS Grid, Flexbox and other new properties
Post-Modern CSS: Start learning CSS Grid, Flexbox and other new propertiesPost-Modern CSS: Start learning CSS Grid, Flexbox and other new properties
Post-Modern CSS: Start learning CSS Grid, Flexbox and other new propertiesBryan Robinson
 
Intro to Microsoft Cognitive Services
Intro to Microsoft Cognitive ServicesIntro to Microsoft Cognitive Services
Intro to Microsoft Cognitive ServicesAmanda Lange
 
Building a private CI/CD pipeline with Java and Docker in the Cloud as presen...
Building a private CI/CD pipeline with Java and Docker in the Cloud as presen...Building a private CI/CD pipeline with Java and Docker in the Cloud as presen...
Building a private CI/CD pipeline with Java and Docker in the Cloud as presen...Baruch Sadogursky
 
The Technical Debt Trap
The Technical Debt TrapThe Technical Debt Trap
The Technical Debt TrapDoc Norton
 
Introduction to Machine Learning
Introduction to Machine LearningIntroduction to Machine Learning
Introduction to Machine LearningJames Ward
 
Teaching Elephants to Dance (and Fly!) A Developer's Journey to Digital Trans...
Teaching Elephants to Dance (and Fly!) A Developer's Journey to Digital Trans...Teaching Elephants to Dance (and Fly!) A Developer's Journey to Digital Trans...
Teaching Elephants to Dance (and Fly!) A Developer's Journey to Digital Trans...Burr Sutter
 
Changing the Game with Cloud, Microservices, and DevOps
Changing the Game with Cloud, Microservices, and DevOps Changing the Game with Cloud, Microservices, and DevOps
Changing the Game with Cloud, Microservices, and DevOps Brian Chambers
 
Developing microservices with aggregates (devnexus2017)
Developing microservices with aggregates (devnexus2017)Developing microservices with aggregates (devnexus2017)
Developing microservices with aggregates (devnexus2017)Chris Richardson
 
The hardest part of microservices: your data
The hardest part of microservices: your dataThe hardest part of microservices: your data
The hardest part of microservices: your dataChristian Posta
 
55 New Features in JDK 9
55 New Features in JDK 955 New Features in JDK 9
55 New Features in JDK 9Simon Ritter
 
Java, JCP, Adopt-a-JSR & You DevNexus
Java, JCP, Adopt-a-JSR & You DevNexusJava, JCP, Adopt-a-JSR & You DevNexus
Java, JCP, Adopt-a-JSR & You DevNexusHeather VanCura
 
Avoid the Fail Whale - Design for Availability
Avoid the Fail Whale - Design for AvailabilityAvoid the Fail Whale - Design for Availability
Avoid the Fail Whale - Design for AvailabilityBrian O'Connell
 

Destaque (20)

Reaching the lambda heaven
Reaching the lambda heavenReaching the lambda heaven
Reaching the lambda heaven
 
Certificaciones en Java 2017
Certificaciones en Java 2017Certificaciones en Java 2017
Certificaciones en Java 2017
 
Practical tipsmakemobilefaster oscon2016
Practical tipsmakemobilefaster oscon2016Practical tipsmakemobilefaster oscon2016
Practical tipsmakemobilefaster oscon2016
 
Java Puzzlers NG S02: Down the Rabbit Hole as presented at DevNexus 2017
Java Puzzlers NG S02: Down the Rabbit Hole as presented at DevNexus 2017Java Puzzlers NG S02: Down the Rabbit Hole as presented at DevNexus 2017
Java Puzzlers NG S02: Down the Rabbit Hole as presented at DevNexus 2017
 
Developing Android applications with Ceylon
Developing Android applications with Ceylon Developing Android applications with Ceylon
Developing Android applications with Ceylon
 
DevOps @Scale (Greek Tragedy in 3 Acts) as it was presented at DevNexus 2017
DevOps @Scale (Greek Tragedy in 3 Acts) as it was presented at DevNexus 2017DevOps @Scale (Greek Tragedy in 3 Acts) as it was presented at DevNexus 2017
DevOps @Scale (Greek Tragedy in 3 Acts) as it was presented at DevNexus 2017
 
Agile Metrics : Velocity is NOT the Goal - NDC Oslo 2014
Agile Metrics : Velocity is NOT the Goal - NDC Oslo 2014Agile Metrics : Velocity is NOT the Goal - NDC Oslo 2014
Agile Metrics : Velocity is NOT the Goal - NDC Oslo 2014
 
Post-Modern CSS: Start learning CSS Grid, Flexbox and other new properties
Post-Modern CSS: Start learning CSS Grid, Flexbox and other new propertiesPost-Modern CSS: Start learning CSS Grid, Flexbox and other new properties
Post-Modern CSS: Start learning CSS Grid, Flexbox and other new properties
 
Intro to Microsoft Cognitive Services
Intro to Microsoft Cognitive ServicesIntro to Microsoft Cognitive Services
Intro to Microsoft Cognitive Services
 
Building a private CI/CD pipeline with Java and Docker in the Cloud as presen...
Building a private CI/CD pipeline with Java and Docker in the Cloud as presen...Building a private CI/CD pipeline with Java and Docker in the Cloud as presen...
Building a private CI/CD pipeline with Java and Docker in the Cloud as presen...
 
The Technical Debt Trap
The Technical Debt TrapThe Technical Debt Trap
The Technical Debt Trap
 
Introduction to Machine Learning
Introduction to Machine LearningIntroduction to Machine Learning
Introduction to Machine Learning
 
Teaching Elephants to Dance (and Fly!) A Developer's Journey to Digital Trans...
Teaching Elephants to Dance (and Fly!) A Developer's Journey to Digital Trans...Teaching Elephants to Dance (and Fly!) A Developer's Journey to Digital Trans...
Teaching Elephants to Dance (and Fly!) A Developer's Journey to Digital Trans...
 
Changing the Game with Cloud, Microservices, and DevOps
Changing the Game with Cloud, Microservices, and DevOps Changing the Game with Cloud, Microservices, and DevOps
Changing the Game with Cloud, Microservices, and DevOps
 
The new Netflix API
The new Netflix APIThe new Netflix API
The new Netflix API
 
Developing microservices with aggregates (devnexus2017)
Developing microservices with aggregates (devnexus2017)Developing microservices with aggregates (devnexus2017)
Developing microservices with aggregates (devnexus2017)
 
The hardest part of microservices: your data
The hardest part of microservices: your dataThe hardest part of microservices: your data
The hardest part of microservices: your data
 
55 New Features in JDK 9
55 New Features in JDK 955 New Features in JDK 9
55 New Features in JDK 9
 
Java, JCP, Adopt-a-JSR & You DevNexus
Java, JCP, Adopt-a-JSR & You DevNexusJava, JCP, Adopt-a-JSR & You DevNexus
Java, JCP, Adopt-a-JSR & You DevNexus
 
Avoid the Fail Whale - Design for Availability
Avoid the Fail Whale - Design for AvailabilityAvoid the Fail Whale - Design for Availability
Avoid the Fail Whale - Design for Availability
 

Semelhante a Generics and Lambda survival guide - DevNexus 2017

Java 8, lambdas, generics: How to survive? - NYC Java Meetup Group
Java 8, lambdas, generics: How to survive? - NYC Java Meetup GroupJava 8, lambdas, generics: How to survive? - NYC Java Meetup Group
Java 8, lambdas, generics: How to survive? - NYC Java Meetup GroupHenri Tremblay
 
JavaOne 2016 - Learn Lambda and functional programming
JavaOne 2016 - Learn Lambda and functional programmingJavaOne 2016 - Learn Lambda and functional programming
JavaOne 2016 - Learn Lambda and functional programmingHenri Tremblay
 
Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Andrew Petryk
 
C# features through examples
C# features through examplesC# features through examples
C# features through examplesZayen Chagra
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesTomer Gabel
 
Java 5 New Feature
Java 5 New FeatureJava 5 New Feature
Java 5 New Featurexcoda
 
1.2 Scala Basics
1.2 Scala Basics1.2 Scala Basics
1.2 Scala Basicsretronym
 
Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3Kirill Rozov
 
Game unleashedjavascript
Game unleashedjavascriptGame unleashedjavascript
Game unleashedjavascriptReece Carlson
 
JAVA OOP project; desperately need help asap im begging.Been stuck.pdf
JAVA OOP project; desperately need help asap im begging.Been stuck.pdfJAVA OOP project; desperately need help asap im begging.Been stuck.pdf
JAVA OOP project; desperately need help asap im begging.Been stuck.pdffantasiatheoutofthef
 
Learning Java 1 – Introduction
Learning Java 1 – IntroductionLearning Java 1 – Introduction
Learning Java 1 – Introductioncaswenson
 

Semelhante a Generics and Lambda survival guide - DevNexus 2017 (20)

Java 8, lambdas, generics: How to survive? - NYC Java Meetup Group
Java 8, lambdas, generics: How to survive? - NYC Java Meetup GroupJava 8, lambdas, generics: How to survive? - NYC Java Meetup Group
Java 8, lambdas, generics: How to survive? - NYC Java Meetup Group
 
JavaOne 2016 - Learn Lambda and functional programming
JavaOne 2016 - Learn Lambda and functional programmingJavaOne 2016 - Learn Lambda and functional programming
JavaOne 2016 - Learn Lambda and functional programming
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)
 
C# features through examples
C# features through examplesC# features through examples
C# features through examples
 
Java generics
Java genericsJava generics
Java generics
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
 
Java 5 Features
Java 5 FeaturesJava 5 Features
Java 5 Features
 
Java byte code in practice
Java byte code in practiceJava byte code in practice
Java byte code in practice
 
Java 5 New Feature
Java 5 New FeatureJava 5 New Feature
Java 5 New Feature
 
1.2 Scala Basics
1.2 Scala Basics1.2 Scala Basics
1.2 Scala Basics
 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
 
Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3
 
Java Cheat Sheet
Java Cheat SheetJava Cheat Sheet
Java Cheat Sheet
 
C++11 - STL Additions
C++11 - STL AdditionsC++11 - STL Additions
C++11 - STL Additions
 
core java
 core java core java
core java
 
What is new in Java 8
What is new in Java 8What is new in Java 8
What is new in Java 8
 
Game unleashedjavascript
Game unleashedjavascriptGame unleashedjavascript
Game unleashedjavascript
 
JAVA OOP project; desperately need help asap im begging.Been stuck.pdf
JAVA OOP project; desperately need help asap im begging.Been stuck.pdfJAVA OOP project; desperately need help asap im begging.Been stuck.pdf
JAVA OOP project; desperately need help asap im begging.Been stuck.pdf
 
Learning Java 1 – Introduction
Learning Java 1 – IntroductionLearning Java 1 – Introduction
Learning Java 1 – Introduction
 

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

call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 

Último (20)

call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 

Generics and Lambda survival guide - DevNexus 2017

  • 1. © Henri Tremblay 2015 Henri Tremblay Senior Software Engineer Terracotta, a Software AG company @henri_tremblay Lambdas and generics survival guide
  • 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”
  • 7. 7 Java 7 End of Life
  • 10. 10 Lambda = Fun with generics Stream<Tweet> stream = Tweet.TWEETS.stream(); Predicate<Tweet> lambda = t -> t.containsHashTag("#lambda"); Collector<Tweet, ?, Map<Boolean, List<Tweet>>> collector = Collectors.partitioningBy(lambda); return stream.collect(collector);
  • 11. 11 What do I need to know? Why
  • 12. 12 What do I need to know? Why Covariance
  • 13. 13 What do I need to know? Why Covariance Capture
  • 14. 14 What do I need to know? Why Covariance Capture Inference
  • 15. 15 What do I need to know? Why Covariance Capture Inference Erasure
  • 16. 16 What do I need to know? Why Covariance Capture Inference Erasure Synthetic
  • 18. 18 Dreaded warnings Type safety: The expression of type List needs unchecked conversion to conform to List<String> Type safety: Unchecked cast from List<capture#1-of ?> to List<String>
  • 21. 21 Rule #1 A code compiling without warning should never ever cause a ClassCastException
  • 23. 23 Arrays Arrays are covariant: Number n = Integer.MAX_VALUE; Number[] list = new Integer[0]; Generics are not: List<Number> l = new ArrayList<Integer>(); // Illegal
  • 24. 24 Why not? List<Integer> li = new ArrayList<Integer>(); List<Number> ln = li; // illegal ln.add(new Float(3.1415)); int i = li.get(0); // ClassCastException Would work if covariant And allow to break rule #1
  • 25. 25 Why for array? Integer[] list = // ... foo(list); public void foo(Object[] o) { // ... }
  • 26. 26 Arrays and generics don’t mix well Can’t have an array of generics List<String>[] lsa = new List<String>[10];// illegal
  • 27. 27 Because If it was allowed List<String>[] lsa = new List<String>[10]; // illegal Object[] oa = lsa; // OK (covariant) oa[0] = new ArrayList<Integer>(); // OK oa[0].add(42); String s = lsa[0].get(0); // bad
  • 28. 28 Exception List<?>[] l = new ArrayList<?>[3];
  • 29. 29 @SafeVarargs // Not actually safe! static void m(List<String>... stringLists) { Object[] array = stringLists; List<Integer> tmpList = Arrays.asList(42); array[0] = tmpList; // Semantically invalid, but compiles without warnings String s = stringLists[0].get(0); // ClassCastException } @SafeVarargs (Java 7)
  • 31. 31 Capture usually is Type List<?> bar(); <T> IExpectationSetters<T> expect(T value); void andReturn(T value); // Method of IExpectationSetters expect(bar()).andReturn(new ArrayList<String>()); And you get The method andReturn(List<capture#6-of ?>) in the type IExpectationSetters<List<capture#6-of ?>> is not applicable for the arguments (ArrayList<String>)
  • 32. 32 Detail List<?> bar(); <T> IExpectationSetters<T> expect(T value); void andReturn(T value); expect(bar()).andReturn(new ArrayList<String>()); List<Capture#6> bar = bar(); IExpectationSetters<List<Capture#6>> es = expect(bar()); es.andReturn(List<Capture#6> value);
  • 33. 33 Only solution We need to cast expect((List<String>) bar()) .andReturn(new ArrayList<String>()); But still a warning Type safety: Unchecked cast from List<capture#6-of ?> to List<String> Framework coder tip: Try to never return a wildcard unless necessary Tell to expect we want a List<String>
  • 35. 35 Diamonds are a programmer best friend List<String> l = new ArrayList<>();
  • 36. 36 How the compiler tells the type <T> T anyObject(T t) <T> T anyObject(Class<T> clazz) The parameterDetermine the return value type
  • 37. 37 How the compiler tells the type MyType var = <T> T anyObject() Determine the return type The assigned variable
  • 38. 38 But watch out with overloading public void foo(String s) public void foo(Object o) foo(anyObject()); Can’t guess the type
  • 39. 39 Trick #1 <T> T anyObject(Class<T> clazz) Artificially give the type with a dedicated parameter Determine the return value type
  • 40. 40 But how to pass a generic? public void foo(String s) public void foo(Object o) foo(anyObject(List<String>.class)); Illegal
  • 41. 41 Some solutions foo((String) anyObject()); foo((List<String>) anyObject()); // Warning This would work But still doesn’t work for generics
  • 42. 42 Trick #2 So the only solution is called a “type witness” foo(EasyMock.<List<String>> anyObject()); … which sadly doesn’t support static imports foo(.<List<String>> anyObject()); // Illegal
  • 43. 43 Trick #2 So the only solution is called a “type witness” foo(EasyMock.<List<String>> anyObject()); … which sadly doesn’t support static imports foo(.<List<String>> anyObject()); // Illegal
  • 44. 44 Trick #2 applied to Lambda return Tweet.TWEETS.stream() .collect( Collectors.<Tweet, Boolean, List<Tweet>, Map<Boolean, List<Tweet>>> groupingBy(t->t.containsHashTag("#lambda"), HashMap::new, ArrayList::new)); Return type: Map<Boolean, List<Tweet>>
  • 45. 45 Lambda = Inference return Tweet.TWEETS.stream() .collect(Collectors .partitioningBy( t->t.containsHashTag("#lambda"));
  • 46. 46 How did it do it? Tweet.TWEETS.stream() List<Tweet> list = Tweet.TWEETS; Stream<Tweet> stream = list.stream();
  • 47. 47 How did it do it? Stream<Tweet> stream = list.stream(); R result = stream.collect(Collector<? super T, ?, R> collector); R result = stream.collect(Collector<? super Tweet, ?, R> collector);
  • 48. 48 How did it do it? stream.collect(Collector<? super Tweet, ?, R> collector); Collector<T, ?, Map<Boolean, List<T>>> collector = Collectors.partitioningBy(Predicate<? super T> predicate); Collector<Tweet, ?, Map<Boolean, List<Tweet>>> collector = Collectors.partitioningBy(Predicate<? super Tweet> predicate);
  • 49. 49 We now know that So the best t can be is a Tweet How did it do it? Predicate<? super Tweet> lambda = t -> t.containsHashTag("#lambda"); Predicate<? super Tweet> lambda = (Tweet t) -> t.containsHashTag("#lambda");
  • 50. 50 Trick #3: Lambda inference Object o = (Runnable) () -> { System.out.println("hi"); }; Collections.sort(strings, (String a, String b) -> a.compareTo(b));
  • 52. 52 Erasure… public void foo() { List<String> l = new ArrayList<String>(); for (String s : l) { System.out.println(s); } } No type public void foo() { List l = new ArrayList(); for (String s : l) { System.out.println(s); } } Compilation
  • 53. 53 … or not erasure public class A extends ArrayList<String> {} public static void main(final String[] args) { ParameterizedType type = (ParameterizedType) A.class.getGenericSuperclass(); System.out.println( type.getActualTypeArguments()[0]); }  prints class java.lang.String
  • 54. 54 Type class java.lang.reflect.Type • GenericArrayType • ParameterizedType • TypeVariable • WildcardType • Implemented by Class java.lang.reflect.GenericDeclaration Implemented by Class, Method, Constructor New powers unleashed!
  • 55. 55 Useful! class A {} abstract class BaseDao<T> { public T load(final long id) { // … } } class ADao extends BaseDao<A> {}
  • 56. 56 Useful! @SuppressWarnings("unchecked") public T load(final long id) { ParameterizedType type = (ParameterizedType) getClass() .getGenericSuperclass(); Type actualType = type.getActualTypeArguments()[0]; return em.find((Class<T>) actualType, (Long) id); } ADao A BaseDao<A> Unsafe cast
  • 58. 58 Everything seems normal… class A<T> { abstract void set(T value); } class B extends A<String> { String value; @Override void set(final String value) { this.value = value; } }
  • 59. 59 But is not class B extends A<String> { void set(String value) { this.value = value; } volatile void set(Object o){ set((String)o); } }
  • 60. 60 Example A a = new B(); a.set(new Object()); But at runtime: java.lang.ClassCastException Raw type warning Perfectly compiling
  • 61. 61 The actual problem being B.class.getDeclaredMethods() volatile void set(java.lang.Object) void B.set(java.lang.String) This Returns that And gives you no way to find out which method is bridged
  • 62. 62 What about lambdas? public class A { public static void main(String[] args) { Method[] methods = A.class.getDeclaredMethods(); Arrays.stream(methods).forEach(m -> System.out.println(m + " " + m.isBridge() + " " + m.isSynthetic())); } }
  • 63. 63 What about lambdas? public class A { public static void main(String[] args) { Method[] methods = A.class.getDeclaredMethods(); Arrays.stream(methods).forEach(m -> System.out.println(m + " " + m.isBridge() + " " + m.isSynthetic())); } } Prints this public static void A.main(java.lang.String[]) false false private static void A.lambda$0(java.lang.reflect.Method) false true
  • 65. 65 What’s wrong? public static Set<Tweet> containing(String hashtag) { return Tweet.TWEETS.stream() .filter(t -> t.hasHashtag(hashtag)) .collect(Collectors.toSet()); }
  • 66. 66 What’s wrong? public static Stream<Tweet> containing(String hashtag) { return Tweet.TWEETS.stream() .filter(t -> t.hasHashtag(hashtag)); } Return a Stream whenever you can
  • 67. 67 What’s wrong? Tweet.TWEETS .stream() .filter(t -> t.hasHashtag("#lambda")) .sorted(Comparator.comparing(Tweet::getSender) .thenComparing(Tweet::getTimestamp)) .forEachOrdered(System.out::println); }
  • 68. 68 What’s wrong? public static void main(String[] args) { getForHashtag("#lambda”).forEachOrdered(System.out::println); } private static Stream<Tweet> getForHashtag(String hashtag) { return Tweet.TWEETS.stream() .filter(hasHashtagPredicate(hashtag)) .sorted(bySenderThenTimestamp()); } private static Predicate<Tweet> hasHashtagPredicate(String hashtag) { return t -> t.hasHashtag(hashtag); } private static Comparator<Tweet> bySenderThenTimestamp() { return Comparator.comparing(Tweet::getSender).thenComparing(Tweet::getTimestamp); } Refactor your one-liner
  • 70. 70 Useful links Ninja Squad – Nice lambda dojo (in French) • http://lambda.ninjackaton.ninja-squad.com/ Brian Goetz - Description of inference types on lambda • http://cr.openjdk.java.net/~briangoetz/lambda/lambda-state-final.html • http://www.slideshare.net/jaxlondon2012/lambda-a-peek-under-the-hood-brian-goetz Angelika Langer - Everything on generics • http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html Maurice Naftalin – Facts and books • http://www.lambdafaq.org/ • Java Generics and Collections: Speed Up the Java Development Process • Mastering Lambdas: Java Programming in a Multicore World

Notas do Editor

  1. Hors le fait que ça nous donne des magnifiques oneliners, on y croise une quantité particulièrement épique de génériques
  2. Malheureusement, quand on le sépare en petits morceaux, nous voyons apparaître des tonnes de génériques. La bonne nouvelle, c’est que ça s’est amélioré. La dernière fois que j’ai donné cette conférence, ça ressemblait plutôt à ça
  3. Et vous terminez, pas trop fier de vous et pas trop sûr d’avoir compris le problème avec un aborable SuppressWarning. Cette session a pour but de vous faire comprendre 1- Pourquoi vous avez ces erreurs 2- Pourquoi c’est fait comme ça 3- Comment c’est implémenté
  4. Et vous terminez, pas trop fier de vous et pas trop sûr d’avoir compris le problème avec un aborable SuppressWarning. Cette session a pour but de vous faire comprendre 1- Pourquoi vous avez ces erreurs 2- Pourquoi c’est fait comme ça 3- Comment c’est implémenté
  5. Et vous terminez, pas trop fier de vous et pas trop sûr d’avoir compris le problème avec un aborable SuppressWarning. Cette session a pour but de vous faire comprendre 1- Pourquoi vous avez ces erreurs 2- Pourquoi c’est fait comme ça 3- Comment c’est implémenté
  6. Et vous terminez, pas trop fier de vous et pas trop sûr d’avoir compris le problème avec un aborable SuppressWarning. Cette session a pour but de vous faire comprendre 1- Pourquoi vous avez ces erreurs 2- Pourquoi c’est fait comme ça 3- Comment c’est implémenté
  7. Et vous terminez, pas trop fier de vous et pas trop sûr d’avoir compris le problème avec un aborable SuppressWarning. Cette session a pour but de vous faire comprendre 1- Pourquoi vous avez ces erreurs 2- Pourquoi c’est fait comme ça 3- Comment c’est implémenté
  8. Et vous terminez, pas trop fier de vous et pas trop sûr d’avoir compris le problème avec un aborable SuppressWarning. Cette session a pour but de vous faire comprendre 1- Pourquoi vous avez ces erreurs 2- Pourquoi c’est fait comme ça 3- Comment c’est implémenté
  9. Emplit de désespoir vous ne savez pas trop comment vous en débarasser parce que toutes vos tentatives ne compilent pas.
  10. Emplit de désespoir vous ne savez pas trop comment vous en débarasser parce que toutes vos tentatives ne compilent pas.
  11. Et vous terminez, pas trop fier de vous et pas trop sûr d’avoir compris le problème avec un aborable SuppressWarning. Cette session a pour but de vous faire comprendre 1- Pourquoi vous avez ces erreurs 2- Pourquoi c’est fait comme ça 3- Comment c’est implémenté
  12. Par exemple, les arrays
  13. C’est cette règle qui a forcé plusieurs décisions de design et qui a par conséquent rendu notre ami le @SuppressWarning si fréquent. On en vient à ce demander comment ils auraient fait si les annotations n’étaient pas apparu au même moment.
  14. Par exemple, les arrays
  15. Les arrays sont covariants. Si on peut assigner un object d’un type donné à un autre type, alors on peut assigner un array d’objet à un array de l’autre type Par contre pour les génériques on ne peut pas. Il est illégal de faire la ligne du bas. Car, un code qui compile sans warning ne doit jamais jamais causé un ClassCastException
  16. Un exemple que vous avez sûrement déjà vu pour expliquer pourquoi c’est interdit. Comme vous voyez, si la covariance était permisse nous briserions la règle #1 Et pour un array
  17. Parce que pour un tableau, on a envie que ça ça passe
  18. On ne peut pas faire de tableau de génériques et c’est bien dommage. Une seule exception, un tableau de wildcard. Le wildcard étant un type quelconque, nous n’avons pas de soucis. Dans tous les autres cas c’est interdit pour la raison suivante
  19. Nous avons le cas suivant. Grâce une asticieuse utilisation de la covariance des arrays, si les arrays génériques étaient permis, nous briserions la règle numéro 1. En résumé, si les designers des génériques avaient laissé tomber la règle pour ce cas et laisser le bénéfice du doute au développeur, nous aurions échappé à plusieurs complexité. Je vous laisse juge de leur décision.
  20. On ne peut pas faire de tableau de génériques et c’est bien dommage. Une seule exception, un tableau de wildcard. Le wildcard étant un type quelconque, nous n’avons pas de soucis. Dans tous les autres cas c’est interdit pour la raison suivante
  21. Par exemple, les arrays
  22. Une méthode retourne un type en wildcard Pour garder la cohérence, le compilateur va fixer le type et l’appeler capture#6 pour s’assurer de la cohérence du type donné à T Pour les développeurs de framework, ne jamais retourner de wildcard si possible
  23. Une méthode retourne un type en wildcard Pour garder la cohérence, le compilateur va fixer le type et l’appeler capture#6 pour s’assurer de la cohérence du type donné à T Pour les développeurs de framework, ne jamais retourner de wildcard si possible
  24. Warning mandatory pour ne pas enfreindre la règle #1
  25. Par exemple, les arrays
  26. Java 7
  27. Lorsqu’il y a un paramètre, le compilateur prend le type du paramètre pour déterminer le type de retour. Cette pour cette raison que le syntaxe que vous voyez est apparu en Java 5. Le paramètre ne sert à rien sauf à fixer le type. Mais ça vous les savez sûrement déjà.
  28. Ensuite s’il n’y a pas de paramètre, le compilateur déduit le type à partir de la variable à laquelle elle est assignée. Mais ça ne marche pas à tous les coups.
  29. Dans les cas d’overloading par exemple. Impossible de deviner quelle méthode doit être appelé
  30. Un truc classique est d’ajouter un paramètre juste pour la bonne cause. C’est un contournement classique.
  31. Dans les cas d’overloading par exemple. Impossible de deviner quelle méthode doit être appelé
  32. Pour les lambda, il est très fort probable d’en avoir besoin. Vous avez ici l’exemple du début où je l’utilisais. Fort heureusement, ce n’est pas nécessaire dans la nouvelle API. Par contre, j’ai un peu de difficulté à vous promettre que ce sera toujours le cas. On touche du bois
  33. Par exemple, les arrays
  34. Everybody knows what is erasure? List<String> and ArrayList<String> got erasure The variable in the loop kept is type Boring, nous on va parler des cas où il n’y a pas d’erasure.
  35. Oh dear, no erasure On récupère la classe parent qui s’avère être générique et implémente donc l’interface ParameterizedType.
  36. Il y a eu un ajout de plusieurs interfaces. Elles sont passées presque complètement inaperçu mais peuvent être utile. Par exemple, l’exemple précédent peut servir à faire ça
  37. Par polymorphisme, le getClass() retourne ADao. Donc la superclass est BaseDao, et le type du paramètre générique est A. And yes, the dumb part if the SuppressWarnings. It comes come the (Class<T>) cast. Since the compiler can’t be sure that actualType is a Class, we get the warning. On ne peut pas s’en débarasser.
  38. Par exemple, les arrays
  39. Vous avez une classe générique étendue par un autre qui fixe le type à String. Rien de plus classique.
  40. Magie, à la décompilation, une nouvelle méthode est apparue. C’est le bridge. Elle ne sert à rien sauf à l’assurer c’est bien une String qui est passé en paramètre. Le volatile c’est parce que la modificateur de champs et de méthodes ont des codes communs. Donc en fait, le décompilateur (jad) a un petit bogue. Attention, Java Decompiler ne vous montrera pas le bridge, il le fait disparaitre. On ne le voit qu’avec Jad qui est moins futé.
  41. La règle #1 n’est pas enfreinte car nous avons un warning. Par contre, Java ajoute dans ce cas particulier une sur-protection. Impossible de s’en prémunir à la compilation. Tout est valide. Il fallait donc combler la faille pour empêcher un Object d’être assigné à une String et amener le chaos et l’anarchie dans la JVM. D’où, le bridge.
  42. Vous avez deux méthodes. L’une déléguant directement à l’autre. Si vous avez un framework faisant des proxies dynamiques ou de l’AOP, vous vous retrouvez avec deux méthodes instrumentées. Et c’est assez rare que c’est ce que vous aviez prévus. Résultat, plus rien ne marche. Par exemple, Spring qui utilise beaucoup de proxies, a dû implémenter une class nommée BridgeMethodResolver qui permet de trouver la méthode concrête appelée par le bridge. Et malheureusement, le JDK n’a pas prévu le coup donc il faut la déduire. C’est ce que j’avais de plus compliqué à vous montrer aujourd’hui. Passons donc à la conclusion.
  43. Revamped API that leverages Java generics and simplifies Cache interactions, Full compatibility with javax.cache API (JSR-107), Offheap storage capabilities, including offheap only caches, Improved performance over Ehcache 2.x, Out of the box Spring Caching integration thanks to the javax.cache support,