SlideShare una empresa de Scribd logo
1 de 23
Iteration 2.0 
Stream 
Martin Skarsaune 
Java Developer and Co-Owner
Iteration Problem 
Root 
x 
y z 
public class Node { 
private Object data; 
private Map<String, Node> children; 
} 
u 
v
Recursion 
• Need to traverse model 
void recursiveX() { 
x(); 
for (final Node child : children.values()) 
child.recursiveX(); 
} 
• recursiveY() 
• recursiveZ() 
• ...
External Iteration : Iterator 
• Any way to implement recursion once and for 
all ? 
• Iterator pattern (Java >= 1.2 ) 
• Wikipedia: 
” the iterator pattern is a design pattern in 
which an iterator is used to traverse a 
container and access the container's 
elements”
Client In Control 
Iterator Behaviour 
Root 
x 
y z 
u 
v 
Client 
Iterator() 
next() 
Iterator
Iterator Issues 
• The iterator instance has state 
– Strong references to provider and internal state 
• implementation often difficult 
• Thread unsafe by design
Internal Iteration - Visitor 
• The visitor pattern 
• Wikipedia: 
” the visitor design pattern is a way of 
separating an algorithm from an object 
structure on which it operates”
Visitor Behaviour 
Provider in Control 
Root 
x 
y z 
u 
v 
Client 
visitor() 
Visitor 
accept(Visitor) 
visit(Node) 
visit(Node) 
visit(Node)
Visitor Implementation 
interface Visitor { 
void visit(Node node); 
} 
void recursiveX() { 
x(); 
for (final Node child : children.values()) 
child.recursiveX(); 
}
Visitor Implementation 
interface Visitor { 
void visit(Node node); 
} 
void accept(Visitor visitor) { 
visitor.visit(this); 
for (final Node child : children.values()) 
child.accept(visitor); 
}
Visitor Usage 
node.accept(n -> n.x()); 
node.accept(n -> n.y()); 
node.accept(n -> n.z());
Visitor – Limitations (Lambda) 
• Limited access to local scope 
– Final and effectively final variables 
• Early exit not possible 
– break 
– return
Internal iteration in Java 8 - 
Stream 
• java.util.Stream 
• Not limited to collections 
• Many powerful methods 
• Potential gains 
– Lazy evaluation 
– Parallell execution 
• The default implementation (StreamSupport) is 
based on (spl)iterators
LIMITATIONS 
callback() 
Stream In Control 
Stream 
Support 
(Spl)Iterator 
Default Stream 
Implementation 
Root 
x 
y z 
u 
v 
stream() Client 
next()
Visitor Stream Implementation 
interface Visitor { 
void visit(Node node); 
}
Visitor Stream Implementation 
- GEneralizaion 
interface Visitor<T> { 
void visit(T node); 
} 
interface Visitable<T> { 
void accept(Visitor<T> visitor); 
}
Visitor Stream Implementation 
- Concrete 
class Node { 
void accept(Visitor visitor){ 
... 
visitor.accept(this); 
... 
} 
}
Visitor Stream Implementation 
- Concrete 
class Node { 
void accept(Visitor<Node> visitor){ 
... 
visitor.accept(this); 
... 
} 
}
Visitor Stream Implementation 
- Concrete 
class Node implements Visitable<Node> { 
void accept(Visitor<Node> visitor){ 
... 
visitor.accept(this); 
... 
} 
}
Visitor Stream Implementation 
- Concrete 
class VisitorStream<T> implements Stream<T> { 
private Visitable<T> source; 
public VisitorStream(Visitable<T> source) { 
this.source = source; 
} 
... 
}
interface Visitor<T> { 
void visit(T node); 
Stream Method Categories 
default boolean isDone(){ 
return false; 
} 
Provider VisitorStream Filter Map 
public void forEach(Consumer<? super T> action) { 
this.source.accept(item -> action.accept(item)); 
} 
} 
✔ ✔ ✔ 
Reduce 
• max 
• min 
• reduce 
• count 
Iterator 
• iterator 
• spliterator 
Concurrency 
• sequential 
• paralell 
Output 
• toArray 
Pipeline 
• filter 
• map 
• flatMap 
• skip(long) 
Stateful 
• sorted 
• distinct 
• ordered 
Short circuit 
• *Match(Predicate) 
• limit(int) 
• find* 
Iteration 
• forEach ✔ 
✔ ✔ 
✔ 
interface SplitVisitable<T> { 
Collection<Visitable<T>> split(); 
} 
implements SortedVisitable ... 
implements DistinctVisitable ... 
implements OrderedVisitable ...
Summary 
• Many advantages to internal iteration 
– Control 
– Simplified implementation 
– Nice abstraction 
• Streams are powerful 
– Create your own – it is not that hard 
Thank You for 
Your Time! 
Martin Skarsaune 
Java Developer and Co-Owner

Más contenido relacionado

Destacado

Utiliser les combinaisons de couleurs
Utiliser les combinaisons de couleursUtiliser les combinaisons de couleurs
Utiliser les combinaisons de couleurssdutot
 
Smoke and mirrors by neil gaiman
Smoke and mirrors   by neil gaimanSmoke and mirrors   by neil gaiman
Smoke and mirrors by neil gaimanNaman Kumar
 
Convention 2011 présentation_gt_cloud finale
Convention 2011 présentation_gt_cloud finaleConvention 2011 présentation_gt_cloud finale
Convention 2011 présentation_gt_cloud finalePatrick Joubert
 
2015.0508創新創業這條路
2015.0508創新創業這條路2015.0508創新創業這條路
2015.0508創新創業這條路Andy Peng
 
2015.0508創新創業這條路2
2015.0508創新創業這條路22015.0508創新創業這條路2
2015.0508創新創業這條路2Andy Peng
 
Cybersecurity: How to Use What We Already Know
Cybersecurity: How to Use What We Already KnowCybersecurity: How to Use What We Already Know
Cybersecurity: How to Use What We Already Knowjxyz
 
IoT gateway dream team - Eclipse Kura and Apache Camel
IoT gateway dream team - Eclipse Kura and Apache CamelIoT gateway dream team - Eclipse Kura and Apache Camel
IoT gateway dream team - Eclipse Kura and Apache CamelHenryk Konsek
 
Jeunesse en action_présentation fr and eng pw pt
Jeunesse en action_présentation fr and eng pw ptJeunesse en action_présentation fr and eng pw pt
Jeunesse en action_présentation fr and eng pw ptGabriel BREZOIU
 
D 3 presentation conf refugies en ukraine
D 3 presentation conf refugies en ukraineD 3 presentation conf refugies en ukraine
D 3 presentation conf refugies en ukraineGabriel BREZOIU
 
Philly ETE 2016: Securing Software by Construction
Philly ETE 2016: Securing Software by ConstructionPhilly ETE 2016: Securing Software by Construction
Philly ETE 2016: Securing Software by Constructionjxyz
 
Productionizing Spark and the Spark Job Server
Productionizing Spark and the Spark Job ServerProductionizing Spark and the Spark Job Server
Productionizing Spark and the Spark Job ServerEvan Chan
 

Destacado (19)

infiDOF - An Overview
infiDOF - An Overview infiDOF - An Overview
infiDOF - An Overview
 
Utiliser les combinaisons de couleurs
Utiliser les combinaisons de couleursUtiliser les combinaisons de couleurs
Utiliser les combinaisons de couleurs
 
JavaZone 2014 - goto java;
JavaZone 2014 - goto java;JavaZone 2014 - goto java;
JavaZone 2014 - goto java;
 
602 pres
602 pres602 pres
602 pres
 
Smoke and mirrors by neil gaiman
Smoke and mirrors   by neil gaimanSmoke and mirrors   by neil gaiman
Smoke and mirrors by neil gaiman
 
Convention 2011 présentation_gt_cloud finale
Convention 2011 présentation_gt_cloud finaleConvention 2011 présentation_gt_cloud finale
Convention 2011 présentation_gt_cloud finale
 
Bring your calculations to Scala!
Bring your calculations to Scala!Bring your calculations to Scala!
Bring your calculations to Scala!
 
Rec101
Rec101Rec101
Rec101
 
Goto devoxx
Goto devoxxGoto devoxx
Goto devoxx
 
2015.0508創新創業這條路
2015.0508創新創業這條路2015.0508創新創業這條路
2015.0508創新創業這條路
 
Smartek Industrial Automation
Smartek Industrial Automation Smartek Industrial Automation
Smartek Industrial Automation
 
2015.0508創新創業這條路2
2015.0508創新創業這條路22015.0508創新創業這條路2
2015.0508創新創業這條路2
 
Cybersecurity: How to Use What We Already Know
Cybersecurity: How to Use What We Already KnowCybersecurity: How to Use What We Already Know
Cybersecurity: How to Use What We Already Know
 
Presentation georgie
Presentation georgiePresentation georgie
Presentation georgie
 
IoT gateway dream team - Eclipse Kura and Apache Camel
IoT gateway dream team - Eclipse Kura and Apache CamelIoT gateway dream team - Eclipse Kura and Apache Camel
IoT gateway dream team - Eclipse Kura and Apache Camel
 
Jeunesse en action_présentation fr and eng pw pt
Jeunesse en action_présentation fr and eng pw ptJeunesse en action_présentation fr and eng pw pt
Jeunesse en action_présentation fr and eng pw pt
 
D 3 presentation conf refugies en ukraine
D 3 presentation conf refugies en ukraineD 3 presentation conf refugies en ukraine
D 3 presentation conf refugies en ukraine
 
Philly ETE 2016: Securing Software by Construction
Philly ETE 2016: Securing Software by ConstructionPhilly ETE 2016: Securing Software by Construction
Philly ETE 2016: Securing Software by Construction
 
Productionizing Spark and the Spark Job Server
Productionizing Spark and the Spark Job ServerProductionizing Spark and the Spark Job Server
Productionizing Spark and the Spark Job Server
 

Similar a JavaZone 2014 - Iteration 2.0: Stream

GR8Conf 2011: Grails Webflow
GR8Conf 2011: Grails WebflowGR8Conf 2011: Grails Webflow
GR8Conf 2011: Grails WebflowGR8Conf
 
​"Delegates, Delegates everywhere" Владимир Миронов
​"Delegates, Delegates everywhere" Владимир Миронов​"Delegates, Delegates everywhere" Владимир Миронов
​"Delegates, Delegates everywhere" Владимир МироновAvitoTech
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaRick Warren
 
Java with a Clojure mindset
Java with a Clojure mindsetJava with a Clojure mindset
Java with a Clojure mindsetDaniel Lebrero
 
Use Kotlin scripts and Clova SDK to build your Clova extension
Use Kotlin scripts and Clova SDK to build your Clova extensionUse Kotlin scripts and Clova SDK to build your Clova extension
Use Kotlin scripts and Clova SDK to build your Clova extensionLINE Corporation
 
Reactor spring one2gx_2013_0902-final
Reactor spring one2gx_2013_0902-finalReactor spring one2gx_2013_0902-final
Reactor spring one2gx_2013_0902-finalStéphane Maldini
 
Phoenix + Reactで 社内システムを 密かに作ってる
Phoenix + Reactで 社内システムを 密かに作ってるPhoenix + Reactで 社内システムを 密かに作ってる
Phoenix + Reactで 社内システムを 密かに作ってるTakahiro Kobaru
 
Reactive Web-Applications @ LambdaDays
Reactive Web-Applications @ LambdaDaysReactive Web-Applications @ LambdaDays
Reactive Web-Applications @ LambdaDaysManuel Bernhardt
 
Deferred Gratification
Deferred GratificationDeferred Gratification
Deferred GratificationTerry Jones
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on AndroidTomáš Kypta
 
Implementing a JavaScript Engine
Implementing a JavaScript EngineImplementing a JavaScript Engine
Implementing a JavaScript EngineKris Mok
 
Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014Jaroslaw Palka
 
How to build rock solid apps & keep 100m+ users happy
How to build rock solid apps & keep 100m+ users happyHow to build rock solid apps & keep 100m+ users happy
How to build rock solid apps & keep 100m+ users happyIordanis (Jordan) Giannakakis
 
JAZOON'13 - Paul Brauner - A backend developer meets the web: my Dart experience
JAZOON'13 - Paul Brauner - A backend developer meets the web: my Dart experienceJAZOON'13 - Paul Brauner - A backend developer meets the web: my Dart experience
JAZOON'13 - Paul Brauner - A backend developer meets the web: my Dart experiencejazoon13
 
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...GeeksLab Odessa
 
Decoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DICDecoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DICKonstantin Kudryashov
 
Angular 2.0: Brighter future?
Angular 2.0: Brighter future?Angular 2.0: Brighter future?
Angular 2.0: Brighter future?Eugene Zharkov
 
Monitoring Your ISP Using InfluxDB Cloud and Raspberry Pi
Monitoring Your ISP Using InfluxDB Cloud and Raspberry PiMonitoring Your ISP Using InfluxDB Cloud and Raspberry Pi
Monitoring Your ISP Using InfluxDB Cloud and Raspberry PiInfluxData
 
Douglas Crockford: Serversideness
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: ServersidenessWebExpo
 

Similar a JavaZone 2014 - Iteration 2.0: Stream (20)

GR8Conf 2011: Grails Webflow
GR8Conf 2011: Grails WebflowGR8Conf 2011: Grails Webflow
GR8Conf 2011: Grails Webflow
 
​"Delegates, Delegates everywhere" Владимир Миронов
​"Delegates, Delegates everywhere" Владимир Миронов​"Delegates, Delegates everywhere" Владимир Миронов
​"Delegates, Delegates everywhere" Владимир Миронов
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
 
Java with a Clojure mindset
Java with a Clojure mindsetJava with a Clojure mindset
Java with a Clojure mindset
 
Use Kotlin scripts and Clova SDK to build your Clova extension
Use Kotlin scripts and Clova SDK to build your Clova extensionUse Kotlin scripts and Clova SDK to build your Clova extension
Use Kotlin scripts and Clova SDK to build your Clova extension
 
Curator intro
Curator introCurator intro
Curator intro
 
Reactor spring one2gx_2013_0902-final
Reactor spring one2gx_2013_0902-finalReactor spring one2gx_2013_0902-final
Reactor spring one2gx_2013_0902-final
 
Phoenix + Reactで 社内システムを 密かに作ってる
Phoenix + Reactで 社内システムを 密かに作ってるPhoenix + Reactで 社内システムを 密かに作ってる
Phoenix + Reactで 社内システムを 密かに作ってる
 
Reactive Web-Applications @ LambdaDays
Reactive Web-Applications @ LambdaDaysReactive Web-Applications @ LambdaDays
Reactive Web-Applications @ LambdaDays
 
Deferred Gratification
Deferred GratificationDeferred Gratification
Deferred Gratification
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on Android
 
Implementing a JavaScript Engine
Implementing a JavaScript EngineImplementing a JavaScript Engine
Implementing a JavaScript Engine
 
Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014
 
How to build rock solid apps & keep 100m+ users happy
How to build rock solid apps & keep 100m+ users happyHow to build rock solid apps & keep 100m+ users happy
How to build rock solid apps & keep 100m+ users happy
 
JAZOON'13 - Paul Brauner - A backend developer meets the web: my Dart experience
JAZOON'13 - Paul Brauner - A backend developer meets the web: my Dart experienceJAZOON'13 - Paul Brauner - A backend developer meets the web: my Dart experience
JAZOON'13 - Paul Brauner - A backend developer meets the web: my Dart experience
 
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
 
Decoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DICDecoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DIC
 
Angular 2.0: Brighter future?
Angular 2.0: Brighter future?Angular 2.0: Brighter future?
Angular 2.0: Brighter future?
 
Monitoring Your ISP Using InfluxDB Cloud and Raspberry Pi
Monitoring Your ISP Using InfluxDB Cloud and Raspberry PiMonitoring Your ISP Using InfluxDB Cloud and Raspberry Pi
Monitoring Your ISP Using InfluxDB Cloud and Raspberry Pi
 
Douglas Crockford: Serversideness
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: Serversideness
 

Más de Martin (高馬丁) Skarsaune (8)

jmc-devoxx.pptx
jmc-devoxx.pptxjmc-devoxx.pptx
jmc-devoxx.pptx
 
Flight recordings and mission control through thick clouds
Flight recordings and mission control through thick cloudsFlight recordings and mission control through thick clouds
Flight recordings and mission control through thick clouds
 
Cloud Collaboration with Eclipse Che
Cloud Collaboration with Eclipse CheCloud Collaboration with Eclipse Che
Cloud Collaboration with Eclipse Che
 
CodeOne Java Debugging Tips
CodeOne Java Debugging TipsCodeOne Java Debugging Tips
CodeOne Java Debugging Tips
 
Java Debugging Tips @oredev
Java Debugging Tips @oredevJava Debugging Tips @oredev
Java Debugging Tips @oredev
 
goto java; (Jfokus)
goto java; (Jfokus)goto java; (Jfokus)
goto java; (Jfokus)
 
Tricks
TricksTricks
Tricks
 
Small Lambda Talk @Booster2015
Small Lambda Talk @Booster2015Small Lambda Talk @Booster2015
Small Lambda Talk @Booster2015
 

Último

A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 

Último (20)

A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 

JavaZone 2014 - Iteration 2.0: Stream

  • 1. Iteration 2.0 Stream Martin Skarsaune Java Developer and Co-Owner
  • 2. Iteration Problem Root x y z public class Node { private Object data; private Map<String, Node> children; } u v
  • 3. Recursion • Need to traverse model void recursiveX() { x(); for (final Node child : children.values()) child.recursiveX(); } • recursiveY() • recursiveZ() • ...
  • 4. External Iteration : Iterator • Any way to implement recursion once and for all ? • Iterator pattern (Java >= 1.2 ) • Wikipedia: ” the iterator pattern is a design pattern in which an iterator is used to traverse a container and access the container's elements”
  • 5. Client In Control Iterator Behaviour Root x y z u v Client Iterator() next() Iterator
  • 6. Iterator Issues • The iterator instance has state – Strong references to provider and internal state • implementation often difficult • Thread unsafe by design
  • 7. Internal Iteration - Visitor • The visitor pattern • Wikipedia: ” the visitor design pattern is a way of separating an algorithm from an object structure on which it operates”
  • 8. Visitor Behaviour Provider in Control Root x y z u v Client visitor() Visitor accept(Visitor) visit(Node) visit(Node) visit(Node)
  • 9. Visitor Implementation interface Visitor { void visit(Node node); } void recursiveX() { x(); for (final Node child : children.values()) child.recursiveX(); }
  • 10. Visitor Implementation interface Visitor { void visit(Node node); } void accept(Visitor visitor) { visitor.visit(this); for (final Node child : children.values()) child.accept(visitor); }
  • 11. Visitor Usage node.accept(n -> n.x()); node.accept(n -> n.y()); node.accept(n -> n.z());
  • 12. Visitor – Limitations (Lambda) • Limited access to local scope – Final and effectively final variables • Early exit not possible – break – return
  • 13. Internal iteration in Java 8 - Stream • java.util.Stream • Not limited to collections • Many powerful methods • Potential gains – Lazy evaluation – Parallell execution • The default implementation (StreamSupport) is based on (spl)iterators
  • 14. LIMITATIONS callback() Stream In Control Stream Support (Spl)Iterator Default Stream Implementation Root x y z u v stream() Client next()
  • 15. Visitor Stream Implementation interface Visitor { void visit(Node node); }
  • 16. Visitor Stream Implementation - GEneralizaion interface Visitor<T> { void visit(T node); } interface Visitable<T> { void accept(Visitor<T> visitor); }
  • 17. Visitor Stream Implementation - Concrete class Node { void accept(Visitor visitor){ ... visitor.accept(this); ... } }
  • 18. Visitor Stream Implementation - Concrete class Node { void accept(Visitor<Node> visitor){ ... visitor.accept(this); ... } }
  • 19. Visitor Stream Implementation - Concrete class Node implements Visitable<Node> { void accept(Visitor<Node> visitor){ ... visitor.accept(this); ... } }
  • 20. Visitor Stream Implementation - Concrete class VisitorStream<T> implements Stream<T> { private Visitable<T> source; public VisitorStream(Visitable<T> source) { this.source = source; } ... }
  • 21. interface Visitor<T> { void visit(T node); Stream Method Categories default boolean isDone(){ return false; } Provider VisitorStream Filter Map public void forEach(Consumer<? super T> action) { this.source.accept(item -> action.accept(item)); } } ✔ ✔ ✔ Reduce • max • min • reduce • count Iterator • iterator • spliterator Concurrency • sequential • paralell Output • toArray Pipeline • filter • map • flatMap • skip(long) Stateful • sorted • distinct • ordered Short circuit • *Match(Predicate) • limit(int) • find* Iteration • forEach ✔ ✔ ✔ ✔ interface SplitVisitable<T> { Collection<Visitable<T>> split(); } implements SortedVisitable ... implements DistinctVisitable ... implements OrderedVisitable ...
  • 22. Summary • Many advantages to internal iteration – Control – Simplified implementation – Nice abstraction • Streams are powerful – Create your own – it is not that hard 
  • 23. Thank You for Your Time! Martin Skarsaune Java Developer and Co-Owner

Notas del editor

  1. Welcome everyone to this talk. My name is Martin Skarsaune. I work as a Java Developer at Kantega. Today I am going to talk a bit about iteration in general, in light of the new Stream interface in Java 8.
  2. So, this may be a familiar situation. Your application has some sort of hierarchical data structure. We see that each node has a map of children.
  3. At times there is a need to traverse the structure to apply some sort of business logic. The most intuitive and elegant way to do this is by recursion. So we create a recursiveX method to apply x to all items, …and a recursive method to apply Y …and a recursive method to apply Z And so on
  4. The question then is, are there any alternatives to write all this repetitive code ? It would also be nice if the traversal was not so tightly coupled with the internal structure. Traditionally iterators have been the dominant approach in Java.
  5. So how does iterators work? The provider hands over an iterator instance to the client. From that point on the client drives the iteration. The iterator must have sufficient state and knowledge to know its position and how to proceed to the next item.
  6. There are some inherent drawbacks with the iterator pattern. The iterator instance has state and direct references back to the provider and its internal state. Implementation is often difficult, complex code is more error prone. For me this is the most important drawback. You can of course cheat, as I have done many times. Write a recursive method to return a collection of items and pass an iterator to that collection instead. It may be an ok solution for 100 items, but less so if there are a million. The iterator is limited to sequential execution
  7. So what alternatives do we have? Another design pattern dealing with iteration is the visitor pattern.
  8. Now how does the visitor pattern work compared to the iterator pattern ? Here we see that the provider drives the iteration with callbacks back to the client.
  9. So, how could we use a visitor in our example. First we define a Visitor interface. We see that it only contains one abstract method, and can therefore be used as a functional interface in Java 8. Then we look at the specific recursive method we created initially. How can we generalize it to accommodate the Visitor?
  10. If we make a slight modification to our recursive method. We add the visitor as an argument and call the callback method of the visitor instead of calling x
  11. Now we can easily reuse this method with a lambda argument to reach all elements. To call x …. Or y …. Or z …
  12. So, this seems to be a much more elegant solution to iteration, but what are the drawbacks ? Since the iteration body is implemented as a lambda, there are certain restrictions. You do not have full access to the enclosing method scope, only final and effectively final variables. The iteration will always go through all the items, it is not possible to abort.
  13. So now we have a nice general purpose iteration mechanism. Is there anything more we can achieve? Java 8 introduces a powerful new Stream concept. A stream is as the name implies, a stream of objects. The stream concept is not limited to collections, this is in my eyes a good design decision as stream is a broader concept and the collection API is bloated enough as it is. Streams have many powerful methods, and open a lot of possibilities as the iteration is not controlled by the client. For instance paralell execution and lazily evaluated pipes of streams. The default implementation in Java is called StreamSupport. One disappointing thing is that it is based on iterators.
  14. So what now if we want to add stream support to our datastructure with StreamSupport? In my opinion we get the worst of both worlds. The provider gets the burden of implementing an iterator, while the client is limited by the restrictions of internal iteration. What I would really like is to get rid of the dependency on iterator.
  15. So in what way can we extend our visitor implementation to support stream ? First we generalize our visitor.
  16. Then we introduce a new interface to represent a structure that will accept a visitor
  17. Then we modify the accept method to accept the generic visitor and allow Node to implement the Visitable interface.
  18. But how does this bring us any closer to support for streams. Instead of Javas built in StreamSupport we create a new Stream implementation called VisitorStream based on a Visitable.
  19. The node class may easily now offer a VisitorStream based stream to clients.
  20. I have organized most of the metods into categories. Lets see how we intend to support each of them. First of all ,we do not want to support iterators. 1. Then we look at the very basics. Streams are about iteration. We see that the forEach method is easily implemented in a functional manner where one function wraps another. 2. Output is trivial, we simply put the results in a collection 3. Reduction methods are used to combine all the items of a stream into one result. The implementation is also quite straightforward, 3-4 lines of quite intuitive code 4. By pipeline methods, we mean methods that give new streams on top of other streams. Implementation here is also quite intuitive, a pipeline pattern where the output of the underlying stream is altered by the stream on top. 5. I have categorized some methods as early exit. This means that the result may be obtained without visiting all the items. We could of course let the iteration complete, but it is suboptimal. A quite simple extension to the iterator interface is
  21. There are some inherent drawbacks with the iterator pattern. The iterator instance has state and direct references back to the provider and its internal state. Implementation is often difficult, complex code is more error prone. For me this is the most important drawback. You can of course cheat, as I have done many times. Write a recursive method to return a collection of items and pass an iterator to that collection instead. It may be an ok solution for 100 items, but less so if there are a million. The iterator is limited to sequential execution