SlideShare une entreprise Scribd logo
1  sur  49
Télécharger pour lire hors ligne
JDK8 Functional API 
Justin Lin caterpillar@openhome.cc http://openhome.cc 
1
Agenda 
•Lambda in 10 mins 
•Lambda & Refactoring 
•Stream... 
•Reduction 
•Parallelism 
•A little Monad 
2
Lambda in 10 mins 
3
•Anonymous class 
•Lambda expressions with no argument 
4
•Lambda expressions with arguments 
•Type inference 
JDK8 built-in functional interface 
5
•Target typing 
•Method reference 
•Default method 
6
Lambda & Refactoring 
7
•The most beneficial way of using lambdas is introducing them into your existing code base. 
8
•Introduce a method. 
Finding tracks over one minute 
9
Collecting names from each track 
10
Filtering tracks over a minute and collecting to a List 
Mapping tracks to names and collecting to a Set 
11
An Intermediate operation, why don't we chain them together? 
Filtering tracks over a minute, mapping tracks to names and collect to a Set 
Well, what's stream? 
We may just use 
map(Track::getName) 
instead. 
12
Stream... 
13
•The stream method returns a Stream instance, not a new collection. 
•The filter or map method returns a Stream instance, too. 
•The collect(toSet()) returns a Set<String> instance as a result. 
14
•The Stream instance draw data from the source, could be a collection, an array, a generator function, or an I/O channel. 
–collection.stream() 
–Arrays.stream(array) 
–Files.lines(Paths.get(fileName)) 
–… 
•An intermediate operation, such as filter, produces a new Stream instance. 
•A terminal operation, such as forEach, produces a non-stream result. 
15
•Intermediate operations are lazy… 
•You don't have to close streams provided by JDK8 except Files.line, list and walk. 
•Compared with the eager way. 
16
•Why does Stream's findFirst return Optional? 
•Maybe there's no the first one … Why not null? 
•Which method of Stream returns Optional? 
–Optional<T> findAny() 
–Optional<T> findFirst() 
–Optional<T> max(Comparator<? super T> comparator) 
–Optional<T> min(Comparator<? super T> comparator) 
–Optional<T> reduce(BinaryOperator<T> accumulator) 
Null sucks. 
Doug Lea 
I call it my billion- dollar mistake. 
Tony Hoare 
17
•Whether an Optional instance containing a value or not is optional, so make appropriate checks to avoid bugs. 
•Creating an Optional instance… 
–Optional.empty() 
–Optional.of(value) 
–Optional.ofNullable(value) 
•Getting the value orXXX? 
–T orElseGet(Supplier<? extends T> other) 
–T orElseThrow(Supplier<? extends X> expsp) 
18
•Checking by yourself? 
•Invoking the specified consumer if a value is present. 
•Invoking the specified consumer if the value matches the given predicate. 
NoSuchElementException if no value. 
19
•Wait! I see wired method signatures in previous examples….Supplier, Consumer, Predicate…What're those types? 
•Important functional interfaces used time and time again in JDK8. 
Interface 
Arguments 
Returns 
Consumer<T> 
T 
void 
Function<T, R> 
T 
R 
Predicate<T> 
T 
boolean 
Supplier<T> 
none 
T 
20
•Consumer<T> 
accept 
T 
void 
21
•Function<T, R> 
–Sub interface: UnaryOperator<T> 
•Predicate<T> 
apply 
T 
R 
apply 
T 
T 
test 
T 
boolean 
Predicate 
Function 
22
•Supplier<T> 
•Fail fast examples if an Optional instance contains no value. 
•Avoiding performance overhead. 
get 
none 
T 
NoSuchElementException 
23
•To avoid performance overheads, the streams library has primitive versions. They have a clear- cut naming convention. 
•Streams for primitives. 
–IntStream 
–LongStream 
–DoubleStream 
•Functional interfaces for primitives. 
–XxxConsumer 
–XxxPredicate 
–XxxSuppiler 
–XxxToOooFunction 
accept 
xxx 
void 
test 
xxx 
boolean 
getAsXxx 
none 
xxx 
applyAsOoo 
xxx 
ooo 
24
•Functional interfaces for mapping objects and primitives. 
–XxxFunction<R> 
–ToXxxFunction<T> 
•Several functional interfaces starts with Bi- prefix. Take BiConsumer<T, U> for an example. 
apply 
xxx 
R 
applyAsXxx 
T 
xxx 
accept 
(T, U) 
void 
25
Reduction 
26
•How long of all long tracks? 
•Reduce? Sometimes it's called as fold(left). 
27
•The max length? 
•Reduction operations 
–Terminal operations that return one value by reducing the contents of a stream. 
–(Reduce, fold or combine, whatever you call it.) 
28
•How to reduce the elements of a stream to a more complex object, such as a collection? 
•Using collect methods… 
29
•The Collectors.toXxx method, such as toSet, doesn't return a Set but a Collector. 
•The Collectors provides factory methods for creating out-of-box Collector … 
•Grouping … 
•Grouping and mapping … 
30
•Grouping and reducing … 
•Grouping and averaging … 
•The stream library picks an appropriate implementation for you. 
31
•You might wish to collect your values into a specific Collection. 
•Implementing your own Collector… 
–supplier、accumulator、combiner、 finisher 
Creating a new mutable result container 
Reducing a value into a mutable result container 
Accepting two partial results and merging them 
Performing an optional final transform on the container 
32
•Implementing your own Collector, a simple example … 
33
Parallelism 
34
•Concurrency 
–Two tasks are making progress at overlapping time periods. 
•Parallelism 
–Two tasks are happening at literally the same time. 
Task 1 
Task 2 
Core 1 
Core 2 
Task 1 Task 2 
Core 1 
Core 2 
35
•Changing a single method call… 
•Making an operation execute in parallel… 
36
•The Java runtime performs a concurrent reduction if … 
–The stream is parallel. 
–The Collector has the characteristic Collector.Characteristics.CONCURRENT 
–Either the stream is unordered, or the Collector has the characteristic Collector.Characteristics.UNORDERED. 
•Built-in concurrent-supported collector 
–groupingByConcurrent 
–toConcurrentMap 
37
•Ordering… 
•The combining function must be associatve when preforming concurrent reduction… 
–1 + 3 + 8 + 9 + 2 + 5 + 4 + 6 + 7 
–(1 + 3) + 8 + (9 + 2) + 5 + (4 + 6 + 7) 
–1 + (3 + 8 )+ 9 + 2 + (5 + 4 + 6 + 7) 
38
•Interference 
•Performance 
–Data size、source data structure、number of cores、cost per element … 
•Simply speaking… 
–Executing in parallel without worrying about tools doesn't mean there is a free lunch. 
Don't do this!! 
ConcurrentModifiedException 
39
A little Monad 
40
•Hey, you forget this … why not refactoring it? 
•Yes! Coming now … But … 
What's flatMap? 
41
•The idea of flatMap is from Monad … 
•Monad? Let's google it …. 
•Great! something can be eaten … XD 
42
•A suggestion: getting started from map and flatMap of Optional … 
•The map method can change the following … 
43
•If your getXXX methods return Optional, you can change the following … 
44
•Monad in Java 8 ? 
–Optional 
–Stream 
–CompletableFuture 
•Several starting points … 
–http://openhome.cc/Gossip/Java/FlatMap.html 
–http://www.codedata.com.tw/java/jdk8- completablefuture/ 
–http://www.slideshare.net/mariofusco/monadic-java 
45
Summary 
•Functional? You've done that when you are … 
–Refactoring your existing code … 
–Applying filter, map, reduce … 
–Returning Optional instead of null … 
–Considering issues of parallelism when using parallel tools, such as parallelStream … 
–Or even using those monadic API of Java 8 … 
•These are Java ways of functional style; pragmatic ways of understanding and introducing Lambda/Functional API 
46
Exercise: 
–Completing Chapter 1 
–Using functional API to refactor Customer again 
47 
MonsterSupreme 
Lambda 就是 重構(重構(程式碼)) 
Lambda is a way to refactor refactored code
References 
•http://shop.oreilly.com/product/0636920030713.do 
•http://www.amazon.com/Refactoring-Improving- Design-Existing-Code/dp/0201485672 
•http://docs.oracle.com/javase/tutorial/collections/streams/index.html 
•http://docs.oracle.com/javase/tutorial/collections/streams/reduction.html 
•http://openhome.cc/Gossip/Java/FlatMap.html 
•http://www.codedata.com.tw/java/jdk8- completablefuture/ 
•http://www.slideshare.net/mariofusco/monadic-java 
48
Thanks!! 
Justin Lin caterpillar@openhome.cc http://openhome.cc 
49

Contenu connexe

Tendances

LINQ Inside
LINQ InsideLINQ Inside
LINQ Insidejeffz
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8LivePerson
 
Scala : language of the future
Scala : language of the futureScala : language of the future
Scala : language of the futureAnsviaLab
 
Modern Programming in Java 8 - Lambdas, Streams and Date Time API
Modern Programming in Java 8 - Lambdas, Streams and Date Time APIModern Programming in Java 8 - Lambdas, Streams and Date Time API
Modern Programming in Java 8 - Lambdas, Streams and Date Time APIGanesh Samarthyam
 
使用.NET构建轻量级分布式框架
使用.NET构建轻量级分布式框架使用.NET构建轻量级分布式框架
使用.NET构建轻量级分布式框架jeffz
 
Presentation on overloading
Presentation on overloading Presentation on overloading
Presentation on overloading Charndeep Sekhon
 
Refactoring to Scala DSLs and LiftOff 2009 Recap
Refactoring to Scala DSLs and LiftOff 2009 RecapRefactoring to Scala DSLs and LiftOff 2009 Recap
Refactoring to Scala DSLs and LiftOff 2009 RecapDave Orme
 
A Brief, but Dense, Intro to Scala
A Brief, but Dense, Intro to ScalaA Brief, but Dense, Intro to Scala
A Brief, but Dense, Intro to ScalaDerek Chen-Becker
 
S1 DML Syntax and Invocation
S1 DML Syntax and InvocationS1 DML Syntax and Invocation
S1 DML Syntax and InvocationArvind Surve
 
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov Nayden Gochev
 
07 control+structures
07 control+structures07 control+structures
07 control+structuresbaran19901990
 
Software Uni Conf October 2014
Software Uni Conf October 2014Software Uni Conf October 2014
Software Uni Conf October 2014Nayden Gochev
 
Eclipse Day India 2015 - Java 8 Overview
Eclipse Day India 2015 - Java 8 OverviewEclipse Day India 2015 - Java 8 Overview
Eclipse Day India 2015 - Java 8 OverviewEclipse Day India
 
From Ruby to Scala
From Ruby to ScalaFrom Ruby to Scala
From Ruby to Scalatod esking
 
SoftwareUniversity seminar fast REST Api with Spring
SoftwareUniversity seminar fast REST Api with SpringSoftwareUniversity seminar fast REST Api with Spring
SoftwareUniversity seminar fast REST Api with SpringNayden Gochev
 
Weaving Dataflows with Silk - ScalaMatsuri 2014, Tokyo
Weaving Dataflows with Silk - ScalaMatsuri 2014, TokyoWeaving Dataflows with Silk - ScalaMatsuri 2014, Tokyo
Weaving Dataflows with Silk - ScalaMatsuri 2014, TokyoTaro L. Saito
 
Functional programming and ruby in functional style
Functional programming and ruby in functional styleFunctional programming and ruby in functional style
Functional programming and ruby in functional styleNiranjan Sarade
 

Tendances (20)

LINQ Inside
LINQ InsideLINQ Inside
LINQ Inside
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
 
Scala : language of the future
Scala : language of the futureScala : language of the future
Scala : language of the future
 
Modern Programming in Java 8 - Lambdas, Streams and Date Time API
Modern Programming in Java 8 - Lambdas, Streams and Date Time APIModern Programming in Java 8 - Lambdas, Streams and Date Time API
Modern Programming in Java 8 - Lambdas, Streams and Date Time API
 
Compile time polymorphism
Compile time polymorphismCompile time polymorphism
Compile time polymorphism
 
Java 8 by example!
Java 8 by example!Java 8 by example!
Java 8 by example!
 
使用.NET构建轻量级分布式框架
使用.NET构建轻量级分布式框架使用.NET构建轻量级分布式框架
使用.NET构建轻量级分布式框架
 
Presentation on overloading
Presentation on overloading Presentation on overloading
Presentation on overloading
 
Refactoring to Scala DSLs and LiftOff 2009 Recap
Refactoring to Scala DSLs and LiftOff 2009 RecapRefactoring to Scala DSLs and LiftOff 2009 Recap
Refactoring to Scala DSLs and LiftOff 2009 Recap
 
A Brief, but Dense, Intro to Scala
A Brief, but Dense, Intro to ScalaA Brief, but Dense, Intro to Scala
A Brief, but Dense, Intro to Scala
 
S1 DML Syntax and Invocation
S1 DML Syntax and InvocationS1 DML Syntax and Invocation
S1 DML Syntax and Invocation
 
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
 
Java 8 Bootcamp
Java 8 BootcampJava 8 Bootcamp
Java 8 Bootcamp
 
07 control+structures
07 control+structures07 control+structures
07 control+structures
 
Software Uni Conf October 2014
Software Uni Conf October 2014Software Uni Conf October 2014
Software Uni Conf October 2014
 
Eclipse Day India 2015 - Java 8 Overview
Eclipse Day India 2015 - Java 8 OverviewEclipse Day India 2015 - Java 8 Overview
Eclipse Day India 2015 - Java 8 Overview
 
From Ruby to Scala
From Ruby to ScalaFrom Ruby to Scala
From Ruby to Scala
 
SoftwareUniversity seminar fast REST Api with Spring
SoftwareUniversity seminar fast REST Api with SpringSoftwareUniversity seminar fast REST Api with Spring
SoftwareUniversity seminar fast REST Api with Spring
 
Weaving Dataflows with Silk - ScalaMatsuri 2014, Tokyo
Weaving Dataflows with Silk - ScalaMatsuri 2014, TokyoWeaving Dataflows with Silk - ScalaMatsuri 2014, Tokyo
Weaving Dataflows with Silk - ScalaMatsuri 2014, Tokyo
 
Functional programming and ruby in functional style
Functional programming and ruby in functional styleFunctional programming and ruby in functional style
Functional programming and ruby in functional style
 

Similaire à JDK8 Functional API

Performance van Java 8 en verder - Jeroen Borgers
Performance van Java 8 en verder - Jeroen BorgersPerformance van Java 8 en verder - Jeroen Borgers
Performance van Java 8 en verder - Jeroen BorgersNLJUG
 
Functional Programming in Java
Functional Programming in JavaFunctional Programming in Java
Functional Programming in JavaJim Bethancourt
 
Java 8
Java 8Java 8
Java 8vpulec
 
The joy of functional programming
The joy of functional programmingThe joy of functional programming
The joy of functional programmingSteve Zhang
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streamsjessitron
 
Stream processing from single node to a cluster
Stream processing from single node to a clusterStream processing from single node to a cluster
Stream processing from single node to a clusterGal Marder
 
JVM Memory Model - Yoav Abrahami, Wix
JVM Memory Model - Yoav Abrahami, WixJVM Memory Model - Yoav Abrahami, Wix
JVM Memory Model - Yoav Abrahami, WixCodemotion Tel Aviv
 
The Road to Lambda - Mike Duigou
The Road to Lambda - Mike DuigouThe Road to Lambda - Mike Duigou
The Road to Lambda - Mike Duigoujaxconf
 
Data Summer Conf 2018, “Hands-on with Apache Spark for Beginners (ENG)” — Akm...
Data Summer Conf 2018, “Hands-on with Apache Spark for Beginners (ENG)” — Akm...Data Summer Conf 2018, “Hands-on with Apache Spark for Beginners (ENG)” — Akm...
Data Summer Conf 2018, “Hands-on with Apache Spark for Beginners (ENG)” — Akm...Provectus
 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project LambdaRahman USTA
 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 itiAhmed mar3y
 
Memory Management with Java and C++
Memory Management with Java and C++Memory Management with Java and C++
Memory Management with Java and C++Mohammad Shaker
 
A closure ekon16
A closure ekon16A closure ekon16
A closure ekon16Max Kleiner
 
Saltconf 2016: Salt stack transport and concurrency
Saltconf 2016: Salt stack transport and concurrencySaltconf 2016: Salt stack transport and concurrency
Saltconf 2016: Salt stack transport and concurrencyThomas Jackson
 

Similaire à JDK8 Functional API (20)

Performance van Java 8 en verder - Jeroen Borgers
Performance van Java 8 en verder - Jeroen BorgersPerformance van Java 8 en verder - Jeroen Borgers
Performance van Java 8 en verder - Jeroen Borgers
 
Functional Programming in Java
Functional Programming in JavaFunctional Programming in Java
Functional Programming in Java
 
Streams in Java 8
Streams in Java 8Streams in Java 8
Streams in Java 8
 
Think in linq
Think in linqThink in linq
Think in linq
 
Java 8
Java 8Java 8
Java 8
 
The joy of functional programming
The joy of functional programmingThe joy of functional programming
The joy of functional programming
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streams
 
Stream processing from single node to a cluster
Stream processing from single node to a clusterStream processing from single node to a cluster
Stream processing from single node to a cluster
 
cb streams - gavin pickin
cb streams - gavin pickincb streams - gavin pickin
cb streams - gavin pickin
 
Java 8
Java 8Java 8
Java 8
 
JVM Memory Model - Yoav Abrahami, Wix
JVM Memory Model - Yoav Abrahami, WixJVM Memory Model - Yoav Abrahami, Wix
JVM Memory Model - Yoav Abrahami, Wix
 
The Road to Lambda - Mike Duigou
The Road to Lambda - Mike DuigouThe Road to Lambda - Mike Duigou
The Road to Lambda - Mike Duigou
 
Java8
Java8Java8
Java8
 
Data Summer Conf 2018, “Hands-on with Apache Spark for Beginners (ENG)” — Akm...
Data Summer Conf 2018, “Hands-on with Apache Spark for Beginners (ENG)” — Akm...Data Summer Conf 2018, “Hands-on with Apache Spark for Beginners (ENG)” — Akm...
Data Summer Conf 2018, “Hands-on with Apache Spark for Beginners (ENG)” — Akm...
 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project Lambda
 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 iti
 
Memory Management with Java and C++
Memory Management with Java and C++Memory Management with Java and C++
Memory Management with Java and C++
 
Java 8 stream and c# 3.5
Java 8 stream and c# 3.5Java 8 stream and c# 3.5
Java 8 stream and c# 3.5
 
A closure ekon16
A closure ekon16A closure ekon16
A closure ekon16
 
Saltconf 2016: Salt stack transport and concurrency
Saltconf 2016: Salt stack transport and concurrencySaltconf 2016: Salt stack transport and concurrency
Saltconf 2016: Salt stack transport and concurrency
 

Plus de Justin Lin

Ch14 簡介 Spring Boot
Ch14 簡介 Spring BootCh14 簡介 Spring Boot
Ch14 簡介 Spring BootJustin Lin
 
Ch13 整合 Spring MVC/Security
Ch13 整合 Spring MVC/SecurityCh13 整合 Spring MVC/Security
Ch13 整合 Spring MVC/SecurityJustin Lin
 
Ch12 Spring 起步走
Ch12 Spring 起步走Ch12 Spring 起步走
Ch12 Spring 起步走Justin Lin
 
Ch11 簡介 JavaMail
Ch11 簡介 JavaMailCh11 簡介 JavaMail
Ch11 簡介 JavaMailJustin Lin
 
Ch10 Web 容器安全管理
Ch10 Web 容器安全管理Ch10 Web 容器安全管理
Ch10 Web 容器安全管理Justin Lin
 
Ch09 整合資料庫
Ch09 整合資料庫Ch09 整合資料庫
Ch09 整合資料庫Justin Lin
 
Ch08 自訂標籤
Ch08 自訂標籤Ch08 自訂標籤
Ch08 自訂標籤Justin Lin
 
Ch07 使用 JSTL
Ch07 使用 JSTLCh07 使用 JSTL
Ch07 使用 JSTLJustin Lin
 
Ch06 使用 JSP
Ch06 使用 JSPCh06 使用 JSP
Ch06 使用 JSPJustin Lin
 
Ch05 Servlet 進階 API、過濾器與傾聽器
Ch05 Servlet 進階 API、過濾器與傾聽器Ch05 Servlet 進階 API、過濾器與傾聽器
Ch05 Servlet 進階 API、過濾器與傾聽器Justin Lin
 
Ch04 會話管理
Ch04 會話管理Ch04 會話管理
Ch04 會話管理Justin Lin
 
Ch03 請求與回應
Ch03 請求與回應Ch03 請求與回應
Ch03 請求與回應Justin Lin
 
Ch02 撰寫與設定 Servlet
Ch02 撰寫與設定 ServletCh02 撰寫與設定 Servlet
Ch02 撰寫與設定 ServletJustin Lin
 
CH1. 簡介 Web 應用程式
CH1. 簡介 Web 應用程式CH1. 簡介 Web 應用程式
CH1. 簡介 Web 應用程式Justin Lin
 
14. 進階主題
14. 進階主題14. 進階主題
14. 進階主題Justin Lin
 
13.並行、平行與非同步
13.並行、平行與非同步13.並行、平行與非同步
13.並行、平行與非同步Justin Lin
 
12. 除錯、測試與效能
12. 除錯、測試與效能12. 除錯、測試與效能
12. 除錯、測試與效能Justin Lin
 
11. 常用內建模組
11. 常用內建模組11. 常用內建模組
11. 常用內建模組Justin Lin
 
10. 資料永續與交換
10. 資料永續與交換10. 資料永續與交換
10. 資料永續與交換Justin Lin
 
9. 資料結構
9. 資料結構9. 資料結構
9. 資料結構Justin Lin
 

Plus de Justin Lin (20)

Ch14 簡介 Spring Boot
Ch14 簡介 Spring BootCh14 簡介 Spring Boot
Ch14 簡介 Spring Boot
 
Ch13 整合 Spring MVC/Security
Ch13 整合 Spring MVC/SecurityCh13 整合 Spring MVC/Security
Ch13 整合 Spring MVC/Security
 
Ch12 Spring 起步走
Ch12 Spring 起步走Ch12 Spring 起步走
Ch12 Spring 起步走
 
Ch11 簡介 JavaMail
Ch11 簡介 JavaMailCh11 簡介 JavaMail
Ch11 簡介 JavaMail
 
Ch10 Web 容器安全管理
Ch10 Web 容器安全管理Ch10 Web 容器安全管理
Ch10 Web 容器安全管理
 
Ch09 整合資料庫
Ch09 整合資料庫Ch09 整合資料庫
Ch09 整合資料庫
 
Ch08 自訂標籤
Ch08 自訂標籤Ch08 自訂標籤
Ch08 自訂標籤
 
Ch07 使用 JSTL
Ch07 使用 JSTLCh07 使用 JSTL
Ch07 使用 JSTL
 
Ch06 使用 JSP
Ch06 使用 JSPCh06 使用 JSP
Ch06 使用 JSP
 
Ch05 Servlet 進階 API、過濾器與傾聽器
Ch05 Servlet 進階 API、過濾器與傾聽器Ch05 Servlet 進階 API、過濾器與傾聽器
Ch05 Servlet 進階 API、過濾器與傾聽器
 
Ch04 會話管理
Ch04 會話管理Ch04 會話管理
Ch04 會話管理
 
Ch03 請求與回應
Ch03 請求與回應Ch03 請求與回應
Ch03 請求與回應
 
Ch02 撰寫與設定 Servlet
Ch02 撰寫與設定 ServletCh02 撰寫與設定 Servlet
Ch02 撰寫與設定 Servlet
 
CH1. 簡介 Web 應用程式
CH1. 簡介 Web 應用程式CH1. 簡介 Web 應用程式
CH1. 簡介 Web 應用程式
 
14. 進階主題
14. 進階主題14. 進階主題
14. 進階主題
 
13.並行、平行與非同步
13.並行、平行與非同步13.並行、平行與非同步
13.並行、平行與非同步
 
12. 除錯、測試與效能
12. 除錯、測試與效能12. 除錯、測試與效能
12. 除錯、測試與效能
 
11. 常用內建模組
11. 常用內建模組11. 常用內建模組
11. 常用內建模組
 
10. 資料永續與交換
10. 資料永續與交換10. 資料永續與交換
10. 資料永續與交換
 
9. 資料結構
9. 資料結構9. 資料結構
9. 資料結構
 

Dernier

Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 

Dernier (20)

Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 

JDK8 Functional API

  • 1. JDK8 Functional API Justin Lin caterpillar@openhome.cc http://openhome.cc 1
  • 2. Agenda •Lambda in 10 mins •Lambda & Refactoring •Stream... •Reduction •Parallelism •A little Monad 2
  • 3. Lambda in 10 mins 3
  • 4. •Anonymous class •Lambda expressions with no argument 4
  • 5. •Lambda expressions with arguments •Type inference JDK8 built-in functional interface 5
  • 6. •Target typing •Method reference •Default method 6
  • 8. •The most beneficial way of using lambdas is introducing them into your existing code base. 8
  • 9. •Introduce a method. Finding tracks over one minute 9
  • 10. Collecting names from each track 10
  • 11. Filtering tracks over a minute and collecting to a List Mapping tracks to names and collecting to a Set 11
  • 12. An Intermediate operation, why don't we chain them together? Filtering tracks over a minute, mapping tracks to names and collect to a Set Well, what's stream? We may just use map(Track::getName) instead. 12
  • 14. •The stream method returns a Stream instance, not a new collection. •The filter or map method returns a Stream instance, too. •The collect(toSet()) returns a Set<String> instance as a result. 14
  • 15. •The Stream instance draw data from the source, could be a collection, an array, a generator function, or an I/O channel. –collection.stream() –Arrays.stream(array) –Files.lines(Paths.get(fileName)) –… •An intermediate operation, such as filter, produces a new Stream instance. •A terminal operation, such as forEach, produces a non-stream result. 15
  • 16. •Intermediate operations are lazy… •You don't have to close streams provided by JDK8 except Files.line, list and walk. •Compared with the eager way. 16
  • 17. •Why does Stream's findFirst return Optional? •Maybe there's no the first one … Why not null? •Which method of Stream returns Optional? –Optional<T> findAny() –Optional<T> findFirst() –Optional<T> max(Comparator<? super T> comparator) –Optional<T> min(Comparator<? super T> comparator) –Optional<T> reduce(BinaryOperator<T> accumulator) Null sucks. Doug Lea I call it my billion- dollar mistake. Tony Hoare 17
  • 18. •Whether an Optional instance containing a value or not is optional, so make appropriate checks to avoid bugs. •Creating an Optional instance… –Optional.empty() –Optional.of(value) –Optional.ofNullable(value) •Getting the value orXXX? –T orElseGet(Supplier<? extends T> other) –T orElseThrow(Supplier<? extends X> expsp) 18
  • 19. •Checking by yourself? •Invoking the specified consumer if a value is present. •Invoking the specified consumer if the value matches the given predicate. NoSuchElementException if no value. 19
  • 20. •Wait! I see wired method signatures in previous examples….Supplier, Consumer, Predicate…What're those types? •Important functional interfaces used time and time again in JDK8. Interface Arguments Returns Consumer<T> T void Function<T, R> T R Predicate<T> T boolean Supplier<T> none T 20
  • 22. •Function<T, R> –Sub interface: UnaryOperator<T> •Predicate<T> apply T R apply T T test T boolean Predicate Function 22
  • 23. •Supplier<T> •Fail fast examples if an Optional instance contains no value. •Avoiding performance overhead. get none T NoSuchElementException 23
  • 24. •To avoid performance overheads, the streams library has primitive versions. They have a clear- cut naming convention. •Streams for primitives. –IntStream –LongStream –DoubleStream •Functional interfaces for primitives. –XxxConsumer –XxxPredicate –XxxSuppiler –XxxToOooFunction accept xxx void test xxx boolean getAsXxx none xxx applyAsOoo xxx ooo 24
  • 25. •Functional interfaces for mapping objects and primitives. –XxxFunction<R> –ToXxxFunction<T> •Several functional interfaces starts with Bi- prefix. Take BiConsumer<T, U> for an example. apply xxx R applyAsXxx T xxx accept (T, U) void 25
  • 27. •How long of all long tracks? •Reduce? Sometimes it's called as fold(left). 27
  • 28. •The max length? •Reduction operations –Terminal operations that return one value by reducing the contents of a stream. –(Reduce, fold or combine, whatever you call it.) 28
  • 29. •How to reduce the elements of a stream to a more complex object, such as a collection? •Using collect methods… 29
  • 30. •The Collectors.toXxx method, such as toSet, doesn't return a Set but a Collector. •The Collectors provides factory methods for creating out-of-box Collector … •Grouping … •Grouping and mapping … 30
  • 31. •Grouping and reducing … •Grouping and averaging … •The stream library picks an appropriate implementation for you. 31
  • 32. •You might wish to collect your values into a specific Collection. •Implementing your own Collector… –supplier、accumulator、combiner、 finisher Creating a new mutable result container Reducing a value into a mutable result container Accepting two partial results and merging them Performing an optional final transform on the container 32
  • 33. •Implementing your own Collector, a simple example … 33
  • 35. •Concurrency –Two tasks are making progress at overlapping time periods. •Parallelism –Two tasks are happening at literally the same time. Task 1 Task 2 Core 1 Core 2 Task 1 Task 2 Core 1 Core 2 35
  • 36. •Changing a single method call… •Making an operation execute in parallel… 36
  • 37. •The Java runtime performs a concurrent reduction if … –The stream is parallel. –The Collector has the characteristic Collector.Characteristics.CONCURRENT –Either the stream is unordered, or the Collector has the characteristic Collector.Characteristics.UNORDERED. •Built-in concurrent-supported collector –groupingByConcurrent –toConcurrentMap 37
  • 38. •Ordering… •The combining function must be associatve when preforming concurrent reduction… –1 + 3 + 8 + 9 + 2 + 5 + 4 + 6 + 7 –(1 + 3) + 8 + (9 + 2) + 5 + (4 + 6 + 7) –1 + (3 + 8 )+ 9 + 2 + (5 + 4 + 6 + 7) 38
  • 39. •Interference •Performance –Data size、source data structure、number of cores、cost per element … •Simply speaking… –Executing in parallel without worrying about tools doesn't mean there is a free lunch. Don't do this!! ConcurrentModifiedException 39
  • 41. •Hey, you forget this … why not refactoring it? •Yes! Coming now … But … What's flatMap? 41
  • 42. •The idea of flatMap is from Monad … •Monad? Let's google it …. •Great! something can be eaten … XD 42
  • 43. •A suggestion: getting started from map and flatMap of Optional … •The map method can change the following … 43
  • 44. •If your getXXX methods return Optional, you can change the following … 44
  • 45. •Monad in Java 8 ? –Optional –Stream –CompletableFuture •Several starting points … –http://openhome.cc/Gossip/Java/FlatMap.html –http://www.codedata.com.tw/java/jdk8- completablefuture/ –http://www.slideshare.net/mariofusco/monadic-java 45
  • 46. Summary •Functional? You've done that when you are … –Refactoring your existing code … –Applying filter, map, reduce … –Returning Optional instead of null … –Considering issues of parallelism when using parallel tools, such as parallelStream … –Or even using those monadic API of Java 8 … •These are Java ways of functional style; pragmatic ways of understanding and introducing Lambda/Functional API 46
  • 47. Exercise: –Completing Chapter 1 –Using functional API to refactor Customer again 47 MonsterSupreme Lambda 就是 重構(重構(程式碼)) Lambda is a way to refactor refactored code
  • 48. References •http://shop.oreilly.com/product/0636920030713.do •http://www.amazon.com/Refactoring-Improving- Design-Existing-Code/dp/0201485672 •http://docs.oracle.com/javase/tutorial/collections/streams/index.html •http://docs.oracle.com/javase/tutorial/collections/streams/reduction.html •http://openhome.cc/Gossip/Java/FlatMap.html •http://www.codedata.com.tw/java/jdk8- completablefuture/ •http://www.slideshare.net/mariofusco/monadic-java 48
  • 49. Thanks!! Justin Lin caterpillar@openhome.cc http://openhome.cc 49