SlideShare a Scribd company logo
Java 8 and .
1
javaBin Oslo – 12.05.2015
Fredrik Vraalsen
fredriv vraalsen@iterate.no
2
Java 8 – what’s new?
Lambdas
Method handles
Extension methods
Streams
Optional
3
Java 8 – what’s new?
Lambdas (anonymous functions)
Method handles
Extension methods
Streams
Optional
4
5
Java 7 vs 8
Collections.sort(people, new Comparator<Person>() {
public int compare(Person x, Person y) {
return x.getName().compareTo(y.getName());
}
});
6
Java 7 vs 8
Collections.sort(people, new Comparator<Person>() {
public int compare(Person x, Person y) {
return x.getName().compareTo(y.getName());
}
});
vs
sort(people, (x, y) -> x.getName().compareTo(y.getName()));
7
Java 7 vs 8
Collections.sort(people, new Comparator<Person>() {
public int compare(Person x, Person y) {
return x.getName().compareTo(y.getName());
}
});
vs
sort(people, comparing(person -> person.getName()));
8
Java 7 vs 8
Collections.sort(people, new Comparator<Person>() {
public int compare(Person x, Person y) {
return x.getName().compareTo(y.getName());
}
});
vs
sort(people, comparing(Person::getName));
9
Java 7 vs 8
Collections.sort(people, new Comparator<Person>() {
public int compare(Person x, Person y) {
return x.getName().compareTo(y.getName());
}
});
vs
people.sort(comparing(Person::getName));
10
Streams
© Fredrik Vraalsen 2008
Old fashioned imperative
12
List<RoadData> filtered = new ArrayList<>();
int count = 0;
for (Iterator<RoadData> i = roadData.iterator();
i.hasNext() && count < 10; ) {
RoadData data = i.next();
if (nameQuery.matches(data.getName())) {
filtered.add(data);
count++;
}
}
Streams
13
roadData.stream()
.filter(data -> nameQuery.matches(data.getName()))
.limit(10)
.collect(toList());
Streams – pipelines
14
roadData.stream()
.filter(data -> nameQuery.matches(data.getName()))
.limit(10)
.collect(toList());
cat roadData.txt | grep … | head > output.txt
Learn you a Stream API
15
Map<String, List<Article>> articlesByCategory =
Learn you a Stream API
16
Map<String, List<Article>> articlesByCategory =
articleTransports.stream()
Learn you a Stream API
17
Map<String, List<Article>> articlesByCategory =
articleTransports.stream()
.map(transport -> convertToArticle(transport))
Learn you a Stream API
18
Map<String, List<Article>> articlesByCategory =
articleTransports.stream()
.map(transport -> convertToArticle(transport))
.collect(groupingBy(article -> article.getCategory()));
Learn you a Stream API
19
Method handles
20
Map<String, List<Article>> articlesByCategory =
articleTransports.stream()
.map(transport -> convertToArticle(transport))
.collect(groupingBy(article -> article.getCategory()));
Map<String, List<Article>> articlesByCategory =
articleTransports.stream()
.map(this::convertToArticle)
.collect(groupingBy(article -> article.getCategory()));
Method handles
21
Method handles
22
Map<String, List<Article>> articlesByCategory =
articleTransports.stream()
.map(this::convertToArticle)
.collect(groupingBy(Article::getCategory));
Naming, caching, counting
23
Map<String, List<Article>> articlesByCategory =
articleTransports.stream()
.map(this::convertToArticle)
.collect(groupingBy(Article::getCategory));
Naming, caching, counting
24
Map<String, List<Article>> articlesByCategory =
articleTransports.stream()
.map(this::transportToArticle)
.collect(groupingBy(Article::category));
Extract functions
25
Map<String, List<Article>> articlesByCategory =
articleTransports.stream()
.map(transportToArticle)
.collect(groupingBy(Article::category));
Function<ArticleTransport, Article> transportToArticle =
transport -> convertToArticle(transport);
Lambdas everywhere!!!1!
links.stream()
.map(link -> link.build())
.forEach(abderaElement::addLink);
26
Old school ifs and fors
links.stream()
.map(link -> link.build())
.forEach(abderaElement::addLink);
for (LinkBuilder lb : links) {

abderaElement.addLink(lb.build());

}
27
Parsing nested JSON
"suggest": {
"tag_suggest": [
{
"length": 5,
"offset": 0,
"options": [
{
"freq": 25,
"score": 0.8,
"text": "fakta"
}
],
"text": "fanta"
}
]
} 28
Lambdas everywhere!!!1!
List<String> terms = new ArrayList<>();

suggestions.getAsJsonObject().getAsJsonArray(“tag_suggest”)

.forEach(tag -> tag.getAsJsonObject().getAsJsonArray("options")

.forEach(option -> terms

.add(option.getAsJsonObject().getAsJsonPrimitive("text")

.getAsString())));

29
Old school ifs and fors
List<String> terms = new ArrayList<>();

for (JsonElement tag : suggestions.getAsJsonObject().getAsJsonArray("tag_suggest")) {

for (JsonElement option : tag.getAsJsonObject().getAsJsonArray("options")) {

terms.add(option.getAsJsonObject().getAsJsonPrimitive("text").getAsString());

}

}

30
Old school ifs and fors
List<String> terms = new ArrayList<>();

for (JsonElement tag : getAll("tag_suggest", suggestions)) {

for (JsonElement option : getAll("options", tag)) {

terms.add(getString("text", option));

}

}

31
List<String> terms = getAll("tag_suggest", suggestions).stream()

.flatMap(tag -> getAll("options", tag).stream())

.map(option -> getString("text", option))

.collect(Collectors.toList());
32
Lambdas everywhere!!!1!
Readability ≫ Style / LOC
Always code as if the person who ends up maintaining your code
is a violent psychopath who knows where you live.
http://c2.com/cgi/wiki?CodeForTheMaintainer
OH NOES
NullPointerException!!?!
© Fredrik Vraalsen 201
Optional<T>
Wrapper object
Make explicit if a value is present or absent (empty)
35
Optional example
public Optional<Image> getImage(Article article)
---
36
Optional example
public Optional<Image> getImage(Article article)
---
Optional<Image> image = getImage(article);
37
Check presence
public Optional<Image> getImage(Article article)
---
Optional<Image> image = getImage(article);
if (image.isPresent()) {
doSomething(image.get());
}
38
Check presence
public Optional<Image> getImage(Article article)
---
Optional<Image> image = getImage(article);
image.ifPresent(img -> doSomething(img));
39
Check presence
public Optional<Image> getImage(Article article)
---
getImage(article).ifPresent(image -> doSomething(image));
40
Default / fallback value
public Optional<Image> getImage(Article article)
---
Image image = getImage(article).orElse(defaultImage);
41
Optional in / Optional out
public Optional<String> getCaption(Optional<Image> image)
---
Optional<Image> image = getImage(article);
Optional<String> caption = getCaption(image);
42
Optional in / Optional out
public String getCaption(Image image)
---
Optional<Image> image = getImage(article);
Optional<String> caption = ???
43
Reaching into the void …
public String getCaption(Image image)
---
Optional<Image> image = getImage(article);
Optional<String> caption = image.map(img -> getCaption(img));
44
Reaching into the void …
public String getCaption(Image image)
---
Optional<String> caption = getImage(article)
.map(img -> getCaption(image));
45
Bye bye NullPointerException?
Marker – this may not return/contain value
Public APIs
Not a general solution to NPEs
46
Optional + Streams = true?
47
Optional + Streams = true?
48
myStream.map(v -> functionReturningOptional(v))
Optional + Streams = true?
49
myStream.map(v -> functionReturningOptional(v))
Stream<Optional<T>>
Optional + Streams = true?
50
myStream.map(v -> functionReturningOptional(v))
Stream<Optional<T>> Stream<T> ???
Guava Optional
51
Iterable<T> presentInstances(Iterable<Optional<T>> optionals)
Optional + Streams = true?
52
public Optional<Image> getImage(Article article)
---
List<Image> images = articles.stream() // Stream<Article>
Optional + Streams = true?
53
public Optional<Image> getImage(Article article)
---
List<Image> images = articles.stream() // Stream<Article>

.map(article -> getImage(article)) // Stream<Optional<Image>>
Optional + Streams = true?
54
public Optional<Image> getImage(Article article)
---
List<Image> images = articles.stream() // Stream<Article>

.map(article -> getImage(article)) // Stream<Optional<Image>>
.filter(Optional::ifPresent)
.map(Optional::get) // Stream<Image>

Optional + Streams = true?
55
public Optional<Image> getImage(Article article)
---
List<Image> images = articles.stream() // Stream<Article>

.map(article -> getImage(article)) // Stream<Optional<Image>>
.filter(Optional::ifPresent)
.map(Optional::get) // Stream<Image>

.collect(toList());
flatMap to the rescue!
flatMap = map + flatten
Stream<Stream<T>> Stream<T>
56
flatMap to the rescue!
flatMap = map + flatten
Stream<Optional<T>> Stream<T> ???
57
flatMap to the rescue!
Easy to create helper functions
Stream<T> toStream(Optional<T> optValue)
58
http://stackoverflow.com/questions/22725537/using-java-8s-optional-with-streamflatmap
Optional + Streams = true?
59
public Optional<Image> getImage(Article article)
---
List<Image> images = articles.stream() // Stream<Article>

.map(article -> getImage(article)) // Stream<Optional<Image>>
.filter(Optional::ifPresent)
.map(Optional::get) // Stream<Image>

.collect(toList());
Optional + Streams = true
60
public Optional<Image> getImage(Article article)
---
List<Image> images = articles.stream() // Stream<Article>

.flatMap(article -> toStream(getImage(article))) // Stream<Image>

.collect(toList());
Optional + Streams = true
61
public Optional<Image> getImage(Article article)
---
List<Image> images = articles.stream() // Stream<Article>

.flatMap(article -> getImage(article).stream()) // Stream<Image>

.collect(toList());
Java 9
https://bugs.openjdk.java.net/browse/JDK-8050820
Take one stream and pass it around…
62
public Stream<Image> getImage(Article article)
---
List<Image> images = articles.stream() // Stream<Article>

.flatMap(article -> getImage(article)) // Stream<Image>

.collect(toList());
No method handle for you!
63
private Article elementToArticle(Map contentById, Element el)
---
List<Article> articles = elements.stream()

.map(el -> elementToArticle(contentById, el))

.collect(toList())
64
http://en.wikipedia.org/wiki/Malabar_matthi_curry#/media/File:Meen_curry_2_(cropped).JPG
Yummy currying!!
65
Mapper mapper = new Mapper(contentById);
---
List<Article> articles = elements.stream()

.map(el -> mapper.elementToArticle(el))

.collect(toList())
Yummy currying!!
66
Mapper mapper = new Mapper(contentById);
---
List<Article> articles = elements.stream()

.map(mapper::elementToArticle)

.collect(toList())
Performance
© Fredrik Vraalsen 2012
Streams – performance
List<Article> frontpageArticles =
frontpage.getArticleIds().stream()
.map(id -> fetchArticle(id))
.collect(toList());
68
This one goes to 11!
List<Article> frontpageArticles =
frontpage.getArticleIds().parallelStream()
.map(id -> fetchArticle(id))
.collect(toList());
69
Starvation
Common F/J thread pool
Workarounds?
Execute within explicit F/J pool
Use CompletableFuture
70
CompletableFuture
Chaining of async futures and actions
Waiting for all or any future(s)
Explicitly complete (like Promise)
Control of executor service
71
http://blog.krecan.net/2014/03/18/how-to-specify-thread-pool-for-java-8-parallel-streams/
http://www.nurkiewicz.com/2013/05/java-8-completablefuture-in-action.html
To parallelStream or not to …
Batch?
parallelStream FTW!
Interactive? Concurrency?
CompletableFuture FTW!
72
Taking the happy path!
Try<RestResponse<ResolvedUri>> resolveURI(URI uri)
---
public ResolvedSectionUri resolveSectionUri(String uri) {
return client.resolveURI(uri))
??? Try<RestResponse<ResolvedUri>>

}
73
Taking the happy path!
Try<RestResponse<ResolvedUri>> resolveURI(URI uri)
---
public ResolvedSectionUri resolveSectionUri(String uri) {
return client.resolveURI(uri))

.map(response -> response.getEntity())

??? Try<Optional<ResolvedUri>>

}
74
Taking the happy path!
Try<RestResponse<ResolvedUri>> resolveURI(URI uri)
---
public ResolvedSectionUri resolveSectionUri(String uri) {
return client.resolveURI(uri))

.map(response -> response.getEntity().get())

??? Try<ResolvedUri>

}
75
Taking the happy path!
Try<RestResponse<ResolvedUri>> resolveURI(URI uri)
---
public ResolvedSectionUri resolveSectionUri(String uri) {
return client.resolveURI(uri))

.map(response -> (ResolvedSectionUri) response.getEntity().get())

??? Try<ResolvedSectionUri>

}
76
Taking the happy path!
Try<RestResponse<ResolvedUri>> resolveURI(URI uri)
---
public ResolvedSectionUri resolveSectionUri(String uri) {
return client.resolveURI(uri))

.map(response -> (ResolvedSectionUri) response.getEntity().get())

.orElse(null);
}
77
Taking the happy path!
Try<RestResponse<ResolvedUri>> resolveURI(URI uri)
---
public ResolvedSectionUri resolveSectionUri(String uri) {
return client.resolveURI(uri))

.map(response -> (ResolvedSectionUri) response.getEntity().get())

.orElseGet(() -> {

log.warn("Cannot resolve section from URI: {}", uri);

return null;

});
}
78
https://github.com/lambdista/try
More cool stuff in Java 8
String join
Collection removeIf (≈ filter)
Map getOrDefault, putIfAbsent, replace, forEach, etc.
java.util.Optional
java.util.stream.Collectors
count, sum, average, min, max, groupingBy, etc.
java.nio.file.Files lines
79
Functional programming
Simpler code
More robust
Better performance
Higher level
Declarative
Less verbose
Less bugs?
81
List<RoadData> filtered = new ArrayList<>();
int count = 0;
for (Iterator<RoadData> i = roadData.iterator();
i.hasNext() && count < 10; ) {
RoadData data = i.next();
if (nameQuery.matches(data.getName())) {
filtered.add(data);
count++;
}
}
roadData.stream()
.filter(data -> nameQuery.matches(data.getName()))
.limit(10)
.collect(toList());
vs.
Pure functions
82
Data In Data Out
Transformation
No external interactions
Functional core
83
————- —— —
—— —- — —- —-
—————
———
—— —- — —- —
————
—— — — — ——-
——- —- — ————
—- ——— ———
———- —— ——
—— - —-
———- — —- — -
Pure functionsI/O I/O
Building blocks
© Fredrik Vraalsen 201
What’s missing?
© Fredrik Vraalsen 2012
What’s missing?
Immutability
Value types
Data structures (lists, maps, etc.)
Concurrency
86
What’s the big deal?
Functional programming is all about values!
And transformations (functions) computing new values
Parallellism vs. Concurrency
Robustness
Testability
87
Some help to be found
Immutable collections
Google Guava, FunctionalJava, clj-ds
Concurrency mechanisms
Akka (Actors, STM)
88
github.com/krukow/clj-ds
PersistentVector<Person> people = Persistents.vector(
new Person("Fredrik", 39),
new Person("Hedda", 3));
89
github.com/krukow/clj-ds
PersistentVector<Person> people = Persistents.vector(
new Person("Fredrik", 39),
new Person("Hedda", 3));
PersistentVector<Person> morePeople =
people.plus(new Person("Johannes", 5));
90
github.com/krukow/clj-ds
PersistentVector<Person> people = Persistents.vector(
new Person("Fredrik", 39),
new Person("Hedda", 3));
PersistentVector<Person> morePeople =
people.plus(new Person("Johannes", 5));
morePeople.stream()
.forEach(p -> System.out.println(p.getName()));
91
Why use X instead?
Java 8 ready for enterprise dev?
JBoss AS, WebSphere – Nope
WildFly, GlassFish, WebLogic, Jetty, Tomcat – OK?
Important things are still missing from Java 8
Clojure and Scala available on JDK 6+!
92
Questions?
© Fredrik Vraalsen 2012
fredriv
vraalsen@iterate.no
Java 8 DOs and DON'Ts - javaBin Oslo May 2015

More Related Content

What's hot

Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
Jonas Bonér
 
The Ring programming language version 1.2 book - Part 24 of 84
The Ring programming language version 1.2 book - Part 24 of 84The Ring programming language version 1.2 book - Part 24 of 84
The Ring programming language version 1.2 book - Part 24 of 84
Mahmoud Samir Fayed
 
R Programming: Learn To Manipulate Strings In R
R Programming: Learn To Manipulate Strings In RR Programming: Learn To Manipulate Strings In R
R Programming: Learn To Manipulate Strings In R
Rsquared Academy
 
Enter The Matrix
Enter The MatrixEnter The Matrix
Enter The Matrix
Mike Anderson
 
R Programming: Export/Output Data In R
R Programming: Export/Output Data In RR Programming: Export/Output Data In R
R Programming: Export/Output Data In R
Rsquared Academy
 
R Basics
R BasicsR Basics
Groovy
GroovyGroovy
TDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
TDC218SP | Trilha Kotlin - DSLs in a Kotlin WayTDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
TDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
tdc-globalcode
 
Collection
CollectionCollection
Collection
Gayathri Ganesh
 
Scala in practice
Scala in practiceScala in practice
Scala in practice
andyrobinson8
 
Giving Clarity to LINQ Queries by Extending Expressions R2
Giving Clarity to LINQ Queries by Extending Expressions R2Giving Clarity to LINQ Queries by Extending Expressions R2
Giving Clarity to LINQ Queries by Extending Expressions R2
Ed Charbeneau
 
mobl
moblmobl
Grails: The search is over
Grails: The search is overGrails: The search is over
Grails: The search is over
Aécio Costa
 
5-minute intro to property-based testing in Python with hypothesis
5-minute intro to property-based testing in Python with hypothesis5-minute intro to property-based testing in Python with hypothesis
5-minute intro to property-based testing in Python with hypothesis
Franklin Chen
 
The Tools for Data Migration Between Oracle , MySQL and Flat Text File.
The Tools for Data Migration Between Oracle , MySQL and Flat Text File.The Tools for Data Migration Between Oracle , MySQL and Flat Text File.
The Tools for Data Migration Between Oracle , MySQL and Flat Text File.
anysql
 
The Ring programming language version 1.8 book - Part 41 of 202
The Ring programming language version 1.8 book - Part 41 of 202The Ring programming language version 1.8 book - Part 41 of 202
The Ring programming language version 1.8 book - Part 41 of 202
Mahmoud Samir Fayed
 
Meet scala
Meet scalaMeet scala
Meet scala
Wojciech Pituła
 
webScrapingFunctions
webScrapingFunctionswebScrapingFunctions
webScrapingFunctions
Hellen Gakuruh
 
ORMLite Android
ORMLite AndroidORMLite Android
ORMLite Android
哲偉 楊
 
3 R Tutorial Data Structure
3 R Tutorial Data Structure3 R Tutorial Data Structure
3 R Tutorial Data Structure
Sakthi Dasans
 

What's hot (20)

Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
The Ring programming language version 1.2 book - Part 24 of 84
The Ring programming language version 1.2 book - Part 24 of 84The Ring programming language version 1.2 book - Part 24 of 84
The Ring programming language version 1.2 book - Part 24 of 84
 
R Programming: Learn To Manipulate Strings In R
R Programming: Learn To Manipulate Strings In RR Programming: Learn To Manipulate Strings In R
R Programming: Learn To Manipulate Strings In R
 
Enter The Matrix
Enter The MatrixEnter The Matrix
Enter The Matrix
 
R Programming: Export/Output Data In R
R Programming: Export/Output Data In RR Programming: Export/Output Data In R
R Programming: Export/Output Data In R
 
R Basics
R BasicsR Basics
R Basics
 
Groovy
GroovyGroovy
Groovy
 
TDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
TDC218SP | Trilha Kotlin - DSLs in a Kotlin WayTDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
TDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
 
Collection
CollectionCollection
Collection
 
Scala in practice
Scala in practiceScala in practice
Scala in practice
 
Giving Clarity to LINQ Queries by Extending Expressions R2
Giving Clarity to LINQ Queries by Extending Expressions R2Giving Clarity to LINQ Queries by Extending Expressions R2
Giving Clarity to LINQ Queries by Extending Expressions R2
 
mobl
moblmobl
mobl
 
Grails: The search is over
Grails: The search is overGrails: The search is over
Grails: The search is over
 
5-minute intro to property-based testing in Python with hypothesis
5-minute intro to property-based testing in Python with hypothesis5-minute intro to property-based testing in Python with hypothesis
5-minute intro to property-based testing in Python with hypothesis
 
The Tools for Data Migration Between Oracle , MySQL and Flat Text File.
The Tools for Data Migration Between Oracle , MySQL and Flat Text File.The Tools for Data Migration Between Oracle , MySQL and Flat Text File.
The Tools for Data Migration Between Oracle , MySQL and Flat Text File.
 
The Ring programming language version 1.8 book - Part 41 of 202
The Ring programming language version 1.8 book - Part 41 of 202The Ring programming language version 1.8 book - Part 41 of 202
The Ring programming language version 1.8 book - Part 41 of 202
 
Meet scala
Meet scalaMeet scala
Meet scala
 
webScrapingFunctions
webScrapingFunctionswebScrapingFunctions
webScrapingFunctions
 
ORMLite Android
ORMLite AndroidORMLite Android
ORMLite Android
 
3 R Tutorial Data Structure
3 R Tutorial Data Structure3 R Tutorial Data Structure
3 R Tutorial Data Structure
 

Similar to Java 8 DOs and DON'Ts - javaBin Oslo May 2015

Java 8 - Return of the Java
Java 8 - Return of the JavaJava 8 - Return of the Java
Java 8 - Return of the Java
Fredrik Vraalsen
 
Lambda functions in java 8
Lambda functions in java 8Lambda functions in java 8
Lambda functions in java 8
James Brown
 
Java 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually useJava 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually use
Sharon Rozinsky
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
Dmitry Buzdin
 
Beyond Java: 자바 8을 중심으로 본 자바의 혁신
Beyond Java: 자바 8을 중심으로 본 자바의 혁신Beyond Java: 자바 8을 중심으로 본 자바의 혁신
Beyond Java: 자바 8을 중심으로 본 자바의 혁신
Sungchul Park
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
Mario Fusco
 
What is new in Java 8
What is new in Java 8What is new in Java 8
What is new in Java 8
Sandeep Kr. Singh
 
Monads and Monoids by Oleksiy Dyagilev
Monads and Monoids by Oleksiy DyagilevMonads and Monoids by Oleksiy Dyagilev
Monads and Monoids by Oleksiy Dyagilev
JavaDayUA
 
Introduction to java 8 stream api
Introduction to java 8 stream apiIntroduction to java 8 stream api
Introduction to java 8 stream api
Vladislav sidlyarevich
 
A bit about Scala
A bit about ScalaA bit about Scala
A bit about Scala
Vladimir Parfinenko
 
SF Elixir Meetup - RethinkDB
SF Elixir Meetup - RethinkDBSF Elixir Meetup - RethinkDB
SF Elixir Meetup - RethinkDB
Peter Hamilton
 
Cocoaheads Meetup / Alex Zimin / Swift magic
Cocoaheads Meetup / Alex Zimin / Swift magicCocoaheads Meetup / Alex Zimin / Swift magic
Cocoaheads Meetup / Alex Zimin / Swift magic
Badoo Development
 
Александр Зимин (Alexander Zimin) — Магия Swift
Александр Зимин (Alexander Zimin) — Магия SwiftАлександр Зимин (Alexander Zimin) — Магия Swift
Александр Зимин (Alexander Zimin) — Магия Swift
CocoaHeads
 
Lambda Functions in Java 8
Lambda Functions in Java 8Lambda Functions in Java 8
Lambda Functions in Java 8
Ganesh Samarthyam
 
RESTful Web Services with Jersey
RESTful Web Services with JerseyRESTful Web Services with Jersey
RESTful Web Services with Jersey
Scott Leberknight
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala
Knoldus Inc.
 

Similar to Java 8 DOs and DON'Ts - javaBin Oslo May 2015 (20)

Java 8 - Return of the Java
Java 8 - Return of the JavaJava 8 - Return of the Java
Java 8 - Return of the Java
 
Lambda functions in java 8
Lambda functions in java 8Lambda functions in java 8
Lambda functions in java 8
 
Java 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually useJava 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually use
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
Beyond Java: 자바 8을 중심으로 본 자바의 혁신
Beyond Java: 자바 8을 중심으로 본 자바의 혁신Beyond Java: 자바 8을 중심으로 본 자바의 혁신
Beyond Java: 자바 8을 중심으로 본 자바의 혁신
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
What is new in Java 8
What is new in Java 8What is new in Java 8
What is new in Java 8
 
Monads and Monoids by Oleksiy Dyagilev
Monads and Monoids by Oleksiy DyagilevMonads and Monoids by Oleksiy Dyagilev
Monads and Monoids by Oleksiy Dyagilev
 
Introduction to java 8 stream api
Introduction to java 8 stream apiIntroduction to java 8 stream api
Introduction to java 8 stream api
 
A bit about Scala
A bit about ScalaA bit about Scala
A bit about Scala
 
SF Elixir Meetup - RethinkDB
SF Elixir Meetup - RethinkDBSF Elixir Meetup - RethinkDB
SF Elixir Meetup - RethinkDB
 
Cocoaheads Meetup / Alex Zimin / Swift magic
Cocoaheads Meetup / Alex Zimin / Swift magicCocoaheads Meetup / Alex Zimin / Swift magic
Cocoaheads Meetup / Alex Zimin / Swift magic
 
Александр Зимин (Alexander Zimin) — Магия Swift
Александр Зимин (Alexander Zimin) — Магия SwiftАлександр Зимин (Alexander Zimin) — Магия Swift
Александр Зимин (Alexander Zimin) — Магия Swift
 
Lambda Functions in Java 8
Lambda Functions in Java 8Lambda Functions in Java 8
Lambda Functions in Java 8
 
RESTful Web Services with Jersey
RESTful Web Services with JerseyRESTful Web Services with Jersey
RESTful Web Services with Jersey
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala
 

More from Fredrik Vraalsen

Building applications with Serverless Framework and AWS Lambda - JavaZone 2019
Building applications with Serverless Framework and AWS Lambda - JavaZone 2019Building applications with Serverless Framework and AWS Lambda - JavaZone 2019
Building applications with Serverless Framework and AWS Lambda - JavaZone 2019
Fredrik Vraalsen
 
Building applications with Serverless Framework and AWS Lambda
Building applications with Serverless Framework and AWS LambdaBuilding applications with Serverless Framework and AWS Lambda
Building applications with Serverless Framework and AWS Lambda
Fredrik Vraalsen
 
Kafka and Kafka Streams in the Global Schibsted Data Platform
Kafka and Kafka Streams in the Global Schibsted Data PlatformKafka and Kafka Streams in the Global Schibsted Data Platform
Kafka and Kafka Streams in the Global Schibsted Data Platform
Fredrik Vraalsen
 
Scala intro workshop
Scala intro workshopScala intro workshop
Scala intro workshop
Fredrik Vraalsen
 
Event stream processing using Kafka streams
Event stream processing using Kafka streamsEvent stream processing using Kafka streams
Event stream processing using Kafka streams
Fredrik Vraalsen
 
Hjelp, vi skal kode funksjonelt i Java!
Hjelp, vi skal kode funksjonelt i Java!Hjelp, vi skal kode funksjonelt i Java!
Hjelp, vi skal kode funksjonelt i Java!
Fredrik Vraalsen
 
Java 8 to the rescue!?
Java 8 to the rescue!?Java 8 to the rescue!?
Java 8 to the rescue!?
Fredrik Vraalsen
 
Git i praksis - erfaringer med overgang fra ClearCase til Git
Git i praksis - erfaringer med overgang fra ClearCase til GitGit i praksis - erfaringer med overgang fra ClearCase til Git
Git i praksis - erfaringer med overgang fra ClearCase til Git
Fredrik Vraalsen
 

More from Fredrik Vraalsen (8)

Building applications with Serverless Framework and AWS Lambda - JavaZone 2019
Building applications with Serverless Framework and AWS Lambda - JavaZone 2019Building applications with Serverless Framework and AWS Lambda - JavaZone 2019
Building applications with Serverless Framework and AWS Lambda - JavaZone 2019
 
Building applications with Serverless Framework and AWS Lambda
Building applications with Serverless Framework and AWS LambdaBuilding applications with Serverless Framework and AWS Lambda
Building applications with Serverless Framework and AWS Lambda
 
Kafka and Kafka Streams in the Global Schibsted Data Platform
Kafka and Kafka Streams in the Global Schibsted Data PlatformKafka and Kafka Streams in the Global Schibsted Data Platform
Kafka and Kafka Streams in the Global Schibsted Data Platform
 
Scala intro workshop
Scala intro workshopScala intro workshop
Scala intro workshop
 
Event stream processing using Kafka streams
Event stream processing using Kafka streamsEvent stream processing using Kafka streams
Event stream processing using Kafka streams
 
Hjelp, vi skal kode funksjonelt i Java!
Hjelp, vi skal kode funksjonelt i Java!Hjelp, vi skal kode funksjonelt i Java!
Hjelp, vi skal kode funksjonelt i Java!
 
Java 8 to the rescue!?
Java 8 to the rescue!?Java 8 to the rescue!?
Java 8 to the rescue!?
 
Git i praksis - erfaringer med overgang fra ClearCase til Git
Git i praksis - erfaringer med overgang fra ClearCase til GitGit i praksis - erfaringer med overgang fra ClearCase til Git
Git i praksis - erfaringer med overgang fra ClearCase til Git
 

Recently uploaded

GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
Alina Yurenko
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
ICS
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
Google
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
Łukasz Chruściel
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
Hornet Dynamics
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Łukasz Chruściel
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
Rakesh Kumar R
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
What is Augmented Reality Image Tracking
What is Augmented Reality Image TrackingWhat is Augmented Reality Image Tracking
What is Augmented Reality Image Tracking
pavan998932
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
TheSMSPoint
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
Octavian Nadolu
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
Green Software Development
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
Philip Schwarz
 
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
kalichargn70th171
 
Microservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we workMicroservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we work
Sven Peters
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
timtebeek1
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
Aftab Hussain
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
Shane Coughlan
 

Recently uploaded (20)

GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
What is Augmented Reality Image Tracking
What is Augmented Reality Image TrackingWhat is Augmented Reality Image Tracking
What is Augmented Reality Image Tracking
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
 
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
 
Microservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we workMicroservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we work
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
 

Java 8 DOs and DON'Ts - javaBin Oslo May 2015

  • 1. Java 8 and . 1 javaBin Oslo – 12.05.2015 Fredrik Vraalsen fredriv vraalsen@iterate.no
  • 2. 2
  • 3. Java 8 – what’s new? Lambdas Method handles Extension methods Streams Optional 3
  • 4. Java 8 – what’s new? Lambdas (anonymous functions) Method handles Extension methods Streams Optional 4
  • 5. 5
  • 6. Java 7 vs 8 Collections.sort(people, new Comparator<Person>() { public int compare(Person x, Person y) { return x.getName().compareTo(y.getName()); } }); 6
  • 7. Java 7 vs 8 Collections.sort(people, new Comparator<Person>() { public int compare(Person x, Person y) { return x.getName().compareTo(y.getName()); } }); vs sort(people, (x, y) -> x.getName().compareTo(y.getName())); 7
  • 8. Java 7 vs 8 Collections.sort(people, new Comparator<Person>() { public int compare(Person x, Person y) { return x.getName().compareTo(y.getName()); } }); vs sort(people, comparing(person -> person.getName())); 8
  • 9. Java 7 vs 8 Collections.sort(people, new Comparator<Person>() { public int compare(Person x, Person y) { return x.getName().compareTo(y.getName()); } }); vs sort(people, comparing(Person::getName)); 9
  • 10. Java 7 vs 8 Collections.sort(people, new Comparator<Person>() { public int compare(Person x, Person y) { return x.getName().compareTo(y.getName()); } }); vs people.sort(comparing(Person::getName)); 10
  • 12. Old fashioned imperative 12 List<RoadData> filtered = new ArrayList<>(); int count = 0; for (Iterator<RoadData> i = roadData.iterator(); i.hasNext() && count < 10; ) { RoadData data = i.next(); if (nameQuery.matches(data.getName())) { filtered.add(data); count++; } }
  • 14. Streams – pipelines 14 roadData.stream() .filter(data -> nameQuery.matches(data.getName())) .limit(10) .collect(toList()); cat roadData.txt | grep … | head > output.txt
  • 15. Learn you a Stream API 15
  • 16. Map<String, List<Article>> articlesByCategory = Learn you a Stream API 16
  • 17. Map<String, List<Article>> articlesByCategory = articleTransports.stream() Learn you a Stream API 17
  • 18. Map<String, List<Article>> articlesByCategory = articleTransports.stream() .map(transport -> convertToArticle(transport)) Learn you a Stream API 18
  • 19. Map<String, List<Article>> articlesByCategory = articleTransports.stream() .map(transport -> convertToArticle(transport)) .collect(groupingBy(article -> article.getCategory())); Learn you a Stream API 19
  • 20. Method handles 20 Map<String, List<Article>> articlesByCategory = articleTransports.stream() .map(transport -> convertToArticle(transport)) .collect(groupingBy(article -> article.getCategory()));
  • 21. Map<String, List<Article>> articlesByCategory = articleTransports.stream() .map(this::convertToArticle) .collect(groupingBy(article -> article.getCategory())); Method handles 21
  • 22. Method handles 22 Map<String, List<Article>> articlesByCategory = articleTransports.stream() .map(this::convertToArticle) .collect(groupingBy(Article::getCategory));
  • 23. Naming, caching, counting 23 Map<String, List<Article>> articlesByCategory = articleTransports.stream() .map(this::convertToArticle) .collect(groupingBy(Article::getCategory));
  • 24. Naming, caching, counting 24 Map<String, List<Article>> articlesByCategory = articleTransports.stream() .map(this::transportToArticle) .collect(groupingBy(Article::category));
  • 25. Extract functions 25 Map<String, List<Article>> articlesByCategory = articleTransports.stream() .map(transportToArticle) .collect(groupingBy(Article::category)); Function<ArticleTransport, Article> transportToArticle = transport -> convertToArticle(transport);
  • 26. Lambdas everywhere!!!1! links.stream() .map(link -> link.build()) .forEach(abderaElement::addLink); 26
  • 27. Old school ifs and fors links.stream() .map(link -> link.build()) .forEach(abderaElement::addLink); for (LinkBuilder lb : links) {
 abderaElement.addLink(lb.build());
 } 27
  • 28. Parsing nested JSON "suggest": { "tag_suggest": [ { "length": 5, "offset": 0, "options": [ { "freq": 25, "score": 0.8, "text": "fakta" } ], "text": "fanta" } ] } 28
  • 29. Lambdas everywhere!!!1! List<String> terms = new ArrayList<>();
 suggestions.getAsJsonObject().getAsJsonArray(“tag_suggest”)
 .forEach(tag -> tag.getAsJsonObject().getAsJsonArray("options")
 .forEach(option -> terms
 .add(option.getAsJsonObject().getAsJsonPrimitive("text")
 .getAsString())));
 29
  • 30. Old school ifs and fors List<String> terms = new ArrayList<>();
 for (JsonElement tag : suggestions.getAsJsonObject().getAsJsonArray("tag_suggest")) {
 for (JsonElement option : tag.getAsJsonObject().getAsJsonArray("options")) {
 terms.add(option.getAsJsonObject().getAsJsonPrimitive("text").getAsString());
 }
 }
 30
  • 31. Old school ifs and fors List<String> terms = new ArrayList<>();
 for (JsonElement tag : getAll("tag_suggest", suggestions)) {
 for (JsonElement option : getAll("options", tag)) {
 terms.add(getString("text", option));
 }
 }
 31
  • 32. List<String> terms = getAll("tag_suggest", suggestions).stream()
 .flatMap(tag -> getAll("options", tag).stream())
 .map(option -> getString("text", option))
 .collect(Collectors.toList()); 32 Lambdas everywhere!!!1!
  • 33. Readability ≫ Style / LOC Always code as if the person who ends up maintaining your code is a violent psychopath who knows where you live. http://c2.com/cgi/wiki?CodeForTheMaintainer
  • 35. Optional<T> Wrapper object Make explicit if a value is present or absent (empty) 35
  • 36. Optional example public Optional<Image> getImage(Article article) --- 36
  • 37. Optional example public Optional<Image> getImage(Article article) --- Optional<Image> image = getImage(article); 37
  • 38. Check presence public Optional<Image> getImage(Article article) --- Optional<Image> image = getImage(article); if (image.isPresent()) { doSomething(image.get()); } 38
  • 39. Check presence public Optional<Image> getImage(Article article) --- Optional<Image> image = getImage(article); image.ifPresent(img -> doSomething(img)); 39
  • 40. Check presence public Optional<Image> getImage(Article article) --- getImage(article).ifPresent(image -> doSomething(image)); 40
  • 41. Default / fallback value public Optional<Image> getImage(Article article) --- Image image = getImage(article).orElse(defaultImage); 41
  • 42. Optional in / Optional out public Optional<String> getCaption(Optional<Image> image) --- Optional<Image> image = getImage(article); Optional<String> caption = getCaption(image); 42
  • 43. Optional in / Optional out public String getCaption(Image image) --- Optional<Image> image = getImage(article); Optional<String> caption = ??? 43
  • 44. Reaching into the void … public String getCaption(Image image) --- Optional<Image> image = getImage(article); Optional<String> caption = image.map(img -> getCaption(img)); 44
  • 45. Reaching into the void … public String getCaption(Image image) --- Optional<String> caption = getImage(article) .map(img -> getCaption(image)); 45
  • 46. Bye bye NullPointerException? Marker – this may not return/contain value Public APIs Not a general solution to NPEs 46
  • 47. Optional + Streams = true? 47
  • 48. Optional + Streams = true? 48 myStream.map(v -> functionReturningOptional(v))
  • 49. Optional + Streams = true? 49 myStream.map(v -> functionReturningOptional(v)) Stream<Optional<T>>
  • 50. Optional + Streams = true? 50 myStream.map(v -> functionReturningOptional(v)) Stream<Optional<T>> Stream<T> ???
  • 52. Optional + Streams = true? 52 public Optional<Image> getImage(Article article) --- List<Image> images = articles.stream() // Stream<Article>
  • 53. Optional + Streams = true? 53 public Optional<Image> getImage(Article article) --- List<Image> images = articles.stream() // Stream<Article>
 .map(article -> getImage(article)) // Stream<Optional<Image>>
  • 54. Optional + Streams = true? 54 public Optional<Image> getImage(Article article) --- List<Image> images = articles.stream() // Stream<Article>
 .map(article -> getImage(article)) // Stream<Optional<Image>> .filter(Optional::ifPresent) .map(Optional::get) // Stream<Image>

  • 55. Optional + Streams = true? 55 public Optional<Image> getImage(Article article) --- List<Image> images = articles.stream() // Stream<Article>
 .map(article -> getImage(article)) // Stream<Optional<Image>> .filter(Optional::ifPresent) .map(Optional::get) // Stream<Image>
 .collect(toList());
  • 56. flatMap to the rescue! flatMap = map + flatten Stream<Stream<T>> Stream<T> 56
  • 57. flatMap to the rescue! flatMap = map + flatten Stream<Optional<T>> Stream<T> ??? 57
  • 58. flatMap to the rescue! Easy to create helper functions Stream<T> toStream(Optional<T> optValue) 58 http://stackoverflow.com/questions/22725537/using-java-8s-optional-with-streamflatmap
  • 59. Optional + Streams = true? 59 public Optional<Image> getImage(Article article) --- List<Image> images = articles.stream() // Stream<Article>
 .map(article -> getImage(article)) // Stream<Optional<Image>> .filter(Optional::ifPresent) .map(Optional::get) // Stream<Image>
 .collect(toList());
  • 60. Optional + Streams = true 60 public Optional<Image> getImage(Article article) --- List<Image> images = articles.stream() // Stream<Article>
 .flatMap(article -> toStream(getImage(article))) // Stream<Image>
 .collect(toList());
  • 61. Optional + Streams = true 61 public Optional<Image> getImage(Article article) --- List<Image> images = articles.stream() // Stream<Article>
 .flatMap(article -> getImage(article).stream()) // Stream<Image>
 .collect(toList()); Java 9 https://bugs.openjdk.java.net/browse/JDK-8050820
  • 62. Take one stream and pass it around… 62 public Stream<Image> getImage(Article article) --- List<Image> images = articles.stream() // Stream<Article>
 .flatMap(article -> getImage(article)) // Stream<Image>
 .collect(toList());
  • 63. No method handle for you! 63 private Article elementToArticle(Map contentById, Element el) --- List<Article> articles = elements.stream()
 .map(el -> elementToArticle(contentById, el))
 .collect(toList())
  • 65. Yummy currying!! 65 Mapper mapper = new Mapper(contentById); --- List<Article> articles = elements.stream()
 .map(el -> mapper.elementToArticle(el))
 .collect(toList())
  • 66. Yummy currying!! 66 Mapper mapper = new Mapper(contentById); --- List<Article> articles = elements.stream()
 .map(mapper::elementToArticle)
 .collect(toList())
  • 68. Streams – performance List<Article> frontpageArticles = frontpage.getArticleIds().stream() .map(id -> fetchArticle(id)) .collect(toList()); 68
  • 69. This one goes to 11! List<Article> frontpageArticles = frontpage.getArticleIds().parallelStream() .map(id -> fetchArticle(id)) .collect(toList()); 69
  • 70. Starvation Common F/J thread pool Workarounds? Execute within explicit F/J pool Use CompletableFuture 70
  • 71. CompletableFuture Chaining of async futures and actions Waiting for all or any future(s) Explicitly complete (like Promise) Control of executor service 71 http://blog.krecan.net/2014/03/18/how-to-specify-thread-pool-for-java-8-parallel-streams/ http://www.nurkiewicz.com/2013/05/java-8-completablefuture-in-action.html
  • 72. To parallelStream or not to … Batch? parallelStream FTW! Interactive? Concurrency? CompletableFuture FTW! 72
  • 73. Taking the happy path! Try<RestResponse<ResolvedUri>> resolveURI(URI uri) --- public ResolvedSectionUri resolveSectionUri(String uri) { return client.resolveURI(uri)) ??? Try<RestResponse<ResolvedUri>>
 } 73
  • 74. Taking the happy path! Try<RestResponse<ResolvedUri>> resolveURI(URI uri) --- public ResolvedSectionUri resolveSectionUri(String uri) { return client.resolveURI(uri))
 .map(response -> response.getEntity())
 ??? Try<Optional<ResolvedUri>>
 } 74
  • 75. Taking the happy path! Try<RestResponse<ResolvedUri>> resolveURI(URI uri) --- public ResolvedSectionUri resolveSectionUri(String uri) { return client.resolveURI(uri))
 .map(response -> response.getEntity().get())
 ??? Try<ResolvedUri>
 } 75
  • 76. Taking the happy path! Try<RestResponse<ResolvedUri>> resolveURI(URI uri) --- public ResolvedSectionUri resolveSectionUri(String uri) { return client.resolveURI(uri))
 .map(response -> (ResolvedSectionUri) response.getEntity().get())
 ??? Try<ResolvedSectionUri>
 } 76
  • 77. Taking the happy path! Try<RestResponse<ResolvedUri>> resolveURI(URI uri) --- public ResolvedSectionUri resolveSectionUri(String uri) { return client.resolveURI(uri))
 .map(response -> (ResolvedSectionUri) response.getEntity().get())
 .orElse(null); } 77
  • 78. Taking the happy path! Try<RestResponse<ResolvedUri>> resolveURI(URI uri) --- public ResolvedSectionUri resolveSectionUri(String uri) { return client.resolveURI(uri))
 .map(response -> (ResolvedSectionUri) response.getEntity().get())
 .orElseGet(() -> {
 log.warn("Cannot resolve section from URI: {}", uri);
 return null;
 }); } 78 https://github.com/lambdista/try
  • 79. More cool stuff in Java 8 String join Collection removeIf (≈ filter) Map getOrDefault, putIfAbsent, replace, forEach, etc. java.util.Optional java.util.stream.Collectors count, sum, average, min, max, groupingBy, etc. java.nio.file.Files lines 79
  • 80. Functional programming Simpler code More robust Better performance
  • 81. Higher level Declarative Less verbose Less bugs? 81 List<RoadData> filtered = new ArrayList<>(); int count = 0; for (Iterator<RoadData> i = roadData.iterator(); i.hasNext() && count < 10; ) { RoadData data = i.next(); if (nameQuery.matches(data.getName())) { filtered.add(data); count++; } } roadData.stream() .filter(data -> nameQuery.matches(data.getName())) .limit(10) .collect(toList()); vs.
  • 82. Pure functions 82 Data In Data Out Transformation No external interactions
  • 83. Functional core 83 ————- —— — —— —- — —- —- ————— ——— —— —- — —- — ———— —— — — — ——- ——- —- — ———— —- ——— ——— ———- —— —— —— - —- ———- — —- — - Pure functionsI/O I/O
  • 86. What’s missing? Immutability Value types Data structures (lists, maps, etc.) Concurrency 86
  • 87. What’s the big deal? Functional programming is all about values! And transformations (functions) computing new values Parallellism vs. Concurrency Robustness Testability 87
  • 88. Some help to be found Immutable collections Google Guava, FunctionalJava, clj-ds Concurrency mechanisms Akka (Actors, STM) 88
  • 89. github.com/krukow/clj-ds PersistentVector<Person> people = Persistents.vector( new Person("Fredrik", 39), new Person("Hedda", 3)); 89
  • 90. github.com/krukow/clj-ds PersistentVector<Person> people = Persistents.vector( new Person("Fredrik", 39), new Person("Hedda", 3)); PersistentVector<Person> morePeople = people.plus(new Person("Johannes", 5)); 90
  • 91. github.com/krukow/clj-ds PersistentVector<Person> people = Persistents.vector( new Person("Fredrik", 39), new Person("Hedda", 3)); PersistentVector<Person> morePeople = people.plus(new Person("Johannes", 5)); morePeople.stream() .forEach(p -> System.out.println(p.getName())); 91
  • 92. Why use X instead? Java 8 ready for enterprise dev? JBoss AS, WebSphere – Nope WildFly, GlassFish, WebLogic, Jetty, Tomcat – OK? Important things are still missing from Java 8 Clojure and Scala available on JDK 6+! 92
  • 93. Questions? © Fredrik Vraalsen 2012 fredriv vraalsen@iterate.no