JDK8 Functional API

Justin Lin
Justin LinTechnology / Community Evangelist at Free lancer
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
1 of 49

Recommended

20160520 what youneedtoknowaboutlambdas by
20160520 what youneedtoknowaboutlambdas20160520 what youneedtoknowaboutlambdas
20160520 what youneedtoknowaboutlambdasshinolajla
971 views39 slides
Java 8 Feature Preview by
Java 8 Feature PreviewJava 8 Feature Preview
Java 8 Feature PreviewJim Bethancourt
522 views51 slides
Lambda Expressions in Java 8 by
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8icarter09
1.9K views32 slides
The Dark Side Of Lambda Expressions in Java 8 by
The Dark Side Of Lambda Expressions in Java 8The Dark Side Of Lambda Expressions in Java 8
The Dark Side Of Lambda Expressions in Java 8Takipi
54.4K views23 slides
Productive Programming in Java 8 - with Lambdas and Streams by
Productive Programming in Java 8 - with Lambdas and Streams Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Ganesh Samarthyam
11.7K views93 slides
camel-scala.pdf by
camel-scala.pdfcamel-scala.pdf
camel-scala.pdfHiroshi Ono
470 views35 slides

More Related Content

What's hot

LINQ Inside by
LINQ InsideLINQ Inside
LINQ Insidejeffz
2K views32 slides
Functional programming with Java 8 by
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8LivePerson
6.9K views76 slides
Scala : language of the future by
Scala : language of the futureScala : language of the future
Scala : language of the futureAnsviaLab
854 views66 slides
Modern Programming in Java 8 - Lambdas, Streams and Date Time API by
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
9.4K views166 slides
Compile time polymorphism by
Compile time polymorphismCompile time polymorphism
Compile time polymorphismForwardBlog Enewzletter
8K views16 slides
Java 8 by example! by
Java 8 by example!Java 8 by example!
Java 8 by example!Mark Harrison
352 views53 slides

What's hot(20)

LINQ Inside by jeffz
LINQ InsideLINQ Inside
LINQ Inside
jeffz2K views
Functional programming with Java 8 by LivePerson
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
LivePerson6.9K views
Scala : language of the future by AnsviaLab
Scala : language of the futureScala : language of the future
Scala : language of the future
AnsviaLab854 views
Modern Programming in Java 8 - Lambdas, Streams and Date Time API by Ganesh Samarthyam
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
Ganesh Samarthyam9.4K views
使用.NET构建轻量级分布式框架 by jeffz
使用.NET构建轻量级分布式框架使用.NET构建轻量级分布式框架
使用.NET构建轻量级分布式框架
jeffz2.2K views
Refactoring to Scala DSLs and LiftOff 2009 Recap by Dave Orme
Refactoring to Scala DSLs and LiftOff 2009 RecapRefactoring to Scala DSLs and LiftOff 2009 Recap
Refactoring to Scala DSLs and LiftOff 2009 Recap
Dave Orme1.2K views
S1 DML Syntax and Invocation by Arvind Surve
S1 DML Syntax and InvocationS1 DML Syntax and Invocation
S1 DML Syntax and Invocation
Arvind Surve196 views
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov by Nayden Gochev
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 Gochev6.2K views
Software Uni Conf October 2014 by Nayden Gochev
Software Uni Conf October 2014Software Uni Conf October 2014
Software Uni Conf October 2014
Nayden Gochev3.8K views
Eclipse Day India 2015 - Java 8 Overview by Eclipse Day India
Eclipse Day India 2015 - Java 8 OverviewEclipse Day India 2015 - Java 8 Overview
Eclipse Day India 2015 - Java 8 Overview
Eclipse Day India809 views
From Ruby to Scala by tod esking
From Ruby to ScalaFrom Ruby to Scala
From Ruby to Scala
tod esking7.9K views
SoftwareUniversity seminar fast REST Api with Spring by Nayden Gochev
SoftwareUniversity seminar fast REST Api with SpringSoftwareUniversity seminar fast REST Api with Spring
SoftwareUniversity seminar fast REST Api with Spring
Nayden Gochev5.1K views
Weaving Dataflows with Silk - ScalaMatsuri 2014, Tokyo by Taro L. Saito
Weaving Dataflows with Silk - ScalaMatsuri 2014, TokyoWeaving Dataflows with Silk - ScalaMatsuri 2014, Tokyo
Weaving Dataflows with Silk - ScalaMatsuri 2014, Tokyo
Taro L. Saito3K views
Functional programming and ruby in functional style by Niranjan Sarade
Functional programming and ruby in functional styleFunctional programming and ruby in functional style
Functional programming and ruby in functional style
Niranjan Sarade2K views

Similar to JDK8 Functional API

Performance van Java 8 en verder - Jeroen Borgers by
Performance van Java 8 en verder - Jeroen BorgersPerformance van Java 8 en verder - Jeroen Borgers
Performance van Java 8 en verder - Jeroen BorgersNLJUG
1.1K views45 slides
Functional Programming in Java by
Functional Programming in JavaFunctional Programming in Java
Functional Programming in JavaJim Bethancourt
86 views34 slides
Streams in Java 8 by
Streams in Java 8Streams in Java 8
Streams in Java 8Tobias Coetzee
1.1K views44 slides
Think in linq by
Think in linqThink in linq
Think in linqSudipta Mukherjee
295 views78 slides
Java 8 by
Java 8Java 8
Java 8vpulec
1.3K views16 slides
The joy of functional programming by
The joy of functional programmingThe joy of functional programming
The joy of functional programmingSteve Zhang
345 views58 slides

Similar to JDK8 Functional API(20)

Performance van Java 8 en verder - Jeroen Borgers by NLJUG
Performance van Java 8 en verder - Jeroen BorgersPerformance van Java 8 en verder - Jeroen Borgers
Performance van Java 8 en verder - Jeroen Borgers
NLJUG1.1K views
Java 8 by vpulec
Java 8Java 8
Java 8
vpulec1.3K views
The joy of functional programming by Steve Zhang
The joy of functional programmingThe joy of functional programming
The joy of functional programming
Steve Zhang345 views
Charles Sharp: Java 8 Streams by jessitron
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streams
jessitron2K views
Stream processing from single node to a cluster by Gal Marder
Stream processing from single node to a clusterStream processing from single node to a cluster
Stream processing from single node to a cluster
Gal Marder279 views
The Road to Lambda - Mike Duigou by jaxconf
The Road to Lambda - Mike DuigouThe Road to Lambda - Mike Duigou
The Road to Lambda - Mike Duigou
jaxconf410 views
Data Summer Conf 2018, “Hands-on with Apache Spark for Beginners (ENG)” — Akm... by Provectus
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...
Provectus92 views
Java 8 - Project Lambda by Rahman USTA
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project Lambda
Rahman USTA5K views
New features in jdk8 iti by Ahmed mar3y
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 iti
Ahmed mar3y79 views
Memory Management with Java and C++ by Mohammad Shaker
Memory Management with Java and C++Memory Management with Java and C++
Memory Management with Java and C++
Mohammad Shaker2.5K views
A closure ekon16 by Max Kleiner
A closure ekon16A closure ekon16
A closure ekon16
Max Kleiner1.1K views
Saltconf 2016: Salt stack transport and concurrency by Thomas Jackson
Saltconf 2016: Salt stack transport and concurrencySaltconf 2016: Salt stack transport and concurrency
Saltconf 2016: Salt stack transport and concurrency
Thomas Jackson2.5K views

More from Justin Lin

Ch14 簡介 Spring Boot by
Ch14 簡介 Spring BootCh14 簡介 Spring Boot
Ch14 簡介 Spring BootJustin Lin
872 views22 slides
Ch13 整合 Spring MVC/Security by
Ch13 整合 Spring MVC/SecurityCh13 整合 Spring MVC/Security
Ch13 整合 Spring MVC/SecurityJustin Lin
280 views58 slides
Ch12 Spring 起步走 by
Ch12 Spring 起步走Ch12 Spring 起步走
Ch12 Spring 起步走Justin Lin
274 views31 slides
Ch11 簡介 JavaMail by
Ch11 簡介 JavaMailCh11 簡介 JavaMail
Ch11 簡介 JavaMailJustin Lin
157 views8 slides
Ch10 Web 容器安全管理 by
Ch10 Web 容器安全管理Ch10 Web 容器安全管理
Ch10 Web 容器安全管理Justin Lin
153 views30 slides
Ch09 整合資料庫 by
Ch09 整合資料庫Ch09 整合資料庫
Ch09 整合資料庫Justin Lin
233 views92 slides

More from Justin Lin(20)

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

Recently uploaded

Cencora Executive Symposium by
Cencora Executive SymposiumCencora Executive Symposium
Cencora Executive Symposiummarketingcommunicati21
159 views14 slides
Backup and Disaster Recovery with CloudStack and StorPool - Workshop - Venko ... by
Backup and Disaster Recovery with CloudStack and StorPool - Workshop - Venko ...Backup and Disaster Recovery with CloudStack and StorPool - Workshop - Venko ...
Backup and Disaster Recovery with CloudStack and StorPool - Workshop - Venko ...ShapeBlue
184 views12 slides
Zero to Cloud Hero: Crafting a Private Cloud from Scratch with XCP-ng, Xen Or... by
Zero to Cloud Hero: Crafting a Private Cloud from Scratch with XCP-ng, Xen Or...Zero to Cloud Hero: Crafting a Private Cloud from Scratch with XCP-ng, Xen Or...
Zero to Cloud Hero: Crafting a Private Cloud from Scratch with XCP-ng, Xen Or...ShapeBlue
198 views20 slides
Business Analyst Series 2023 - Week 4 Session 8 by
Business Analyst Series 2023 -  Week 4 Session 8Business Analyst Series 2023 -  Week 4 Session 8
Business Analyst Series 2023 - Week 4 Session 8DianaGray10
123 views13 slides
Enabling DPU Hardware Accelerators in XCP-ng Cloud Platform Environment - And... by
Enabling DPU Hardware Accelerators in XCP-ng Cloud Platform Environment - And...Enabling DPU Hardware Accelerators in XCP-ng Cloud Platform Environment - And...
Enabling DPU Hardware Accelerators in XCP-ng Cloud Platform Environment - And...ShapeBlue
106 views12 slides
What’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlue by
What’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlueWhat’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlue
What’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlueShapeBlue
263 views23 slides

Recently uploaded(20)

Backup and Disaster Recovery with CloudStack and StorPool - Workshop - Venko ... by ShapeBlue
Backup and Disaster Recovery with CloudStack and StorPool - Workshop - Venko ...Backup and Disaster Recovery with CloudStack and StorPool - Workshop - Venko ...
Backup and Disaster Recovery with CloudStack and StorPool - Workshop - Venko ...
ShapeBlue184 views
Zero to Cloud Hero: Crafting a Private Cloud from Scratch with XCP-ng, Xen Or... by ShapeBlue
Zero to Cloud Hero: Crafting a Private Cloud from Scratch with XCP-ng, Xen Or...Zero to Cloud Hero: Crafting a Private Cloud from Scratch with XCP-ng, Xen Or...
Zero to Cloud Hero: Crafting a Private Cloud from Scratch with XCP-ng, Xen Or...
ShapeBlue198 views
Business Analyst Series 2023 - Week 4 Session 8 by DianaGray10
Business Analyst Series 2023 -  Week 4 Session 8Business Analyst Series 2023 -  Week 4 Session 8
Business Analyst Series 2023 - Week 4 Session 8
DianaGray10123 views
Enabling DPU Hardware Accelerators in XCP-ng Cloud Platform Environment - And... by ShapeBlue
Enabling DPU Hardware Accelerators in XCP-ng Cloud Platform Environment - And...Enabling DPU Hardware Accelerators in XCP-ng Cloud Platform Environment - And...
Enabling DPU Hardware Accelerators in XCP-ng Cloud Platform Environment - And...
ShapeBlue106 views
What’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlue by ShapeBlue
What’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlueWhat’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlue
What’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlue
ShapeBlue263 views
VNF Integration and Support in CloudStack - Wei Zhou - ShapeBlue by ShapeBlue
VNF Integration and Support in CloudStack - Wei Zhou - ShapeBlueVNF Integration and Support in CloudStack - Wei Zhou - ShapeBlue
VNF Integration and Support in CloudStack - Wei Zhou - ShapeBlue
ShapeBlue203 views
Initiating and Advancing Your Strategic GIS Governance Strategy by Safe Software
Initiating and Advancing Your Strategic GIS Governance StrategyInitiating and Advancing Your Strategic GIS Governance Strategy
Initiating and Advancing Your Strategic GIS Governance Strategy
Safe Software176 views
Updates on the LINSTOR Driver for CloudStack - Rene Peinthor - LINBIT by ShapeBlue
Updates on the LINSTOR Driver for CloudStack - Rene Peinthor - LINBITUpdates on the LINSTOR Driver for CloudStack - Rene Peinthor - LINBIT
Updates on the LINSTOR Driver for CloudStack - Rene Peinthor - LINBIT
ShapeBlue206 views
Confidence in CloudStack - Aron Wagner, Nathan Gleason - Americ by ShapeBlue
Confidence in CloudStack - Aron Wagner, Nathan Gleason - AmericConfidence in CloudStack - Aron Wagner, Nathan Gleason - Americ
Confidence in CloudStack - Aron Wagner, Nathan Gleason - Americ
ShapeBlue130 views
Webinar : Desperately Seeking Transformation - Part 2: Insights from leading... by The Digital Insurer
Webinar : Desperately Seeking Transformation - Part 2:  Insights from leading...Webinar : Desperately Seeking Transformation - Part 2:  Insights from leading...
Webinar : Desperately Seeking Transformation - Part 2: Insights from leading...
Transitioning from VMware vCloud to Apache CloudStack: A Path to Profitabilit... by ShapeBlue
Transitioning from VMware vCloud to Apache CloudStack: A Path to Profitabilit...Transitioning from VMware vCloud to Apache CloudStack: A Path to Profitabilit...
Transitioning from VMware vCloud to Apache CloudStack: A Path to Profitabilit...
ShapeBlue159 views
KVM Security Groups Under the Hood - Wido den Hollander - Your.Online by ShapeBlue
KVM Security Groups Under the Hood - Wido den Hollander - Your.OnlineKVM Security Groups Under the Hood - Wido den Hollander - Your.Online
KVM Security Groups Under the Hood - Wido den Hollander - Your.Online
ShapeBlue221 views
Business Analyst Series 2023 - Week 4 Session 7 by DianaGray10
Business Analyst Series 2023 -  Week 4 Session 7Business Analyst Series 2023 -  Week 4 Session 7
Business Analyst Series 2023 - Week 4 Session 7
DianaGray10139 views
Developments to CloudStack’s SDN ecosystem: Integration with VMWare NSX 4 - P... by ShapeBlue
Developments to CloudStack’s SDN ecosystem: Integration with VMWare NSX 4 - P...Developments to CloudStack’s SDN ecosystem: Integration with VMWare NSX 4 - P...
Developments to CloudStack’s SDN ecosystem: Integration with VMWare NSX 4 - P...
ShapeBlue194 views
Centralized Logging Feature in CloudStack using ELK and Grafana - Kiran Chava... by ShapeBlue
Centralized Logging Feature in CloudStack using ELK and Grafana - Kiran Chava...Centralized Logging Feature in CloudStack using ELK and Grafana - Kiran Chava...
Centralized Logging Feature in CloudStack using ELK and Grafana - Kiran Chava...
ShapeBlue145 views
DRBD Deep Dive - Philipp Reisner - LINBIT by ShapeBlue
DRBD Deep Dive - Philipp Reisner - LINBITDRBD Deep Dive - Philipp Reisner - LINBIT
DRBD Deep Dive - Philipp Reisner - LINBIT
ShapeBlue180 views
TrustArc Webinar - Managing Online Tracking Technology Vendors_ A Checklist f... by TrustArc
TrustArc Webinar - Managing Online Tracking Technology Vendors_ A Checklist f...TrustArc Webinar - Managing Online Tracking Technology Vendors_ A Checklist f...
TrustArc Webinar - Managing Online Tracking Technology Vendors_ A Checklist f...
TrustArc170 views
Declarative Kubernetes Cluster Deployment with Cloudstack and Cluster API - O... by ShapeBlue
Declarative Kubernetes Cluster Deployment with Cloudstack and Cluster API - O...Declarative Kubernetes Cluster Deployment with Cloudstack and Cluster API - O...
Declarative Kubernetes Cluster Deployment with Cloudstack and Cluster API - O...
ShapeBlue132 views

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