SlideShare a Scribd company logo
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

More Related Content

Viewers also liked

infiDOF - An Overview
infiDOF - An Overview infiDOF - An Overview
infiDOF - An Overview
Abhinay Kalburgi
 
Utiliser les combinaisons de couleurs
Utiliser les combinaisons de couleursUtiliser les combinaisons de couleurs
Utiliser les combinaisons de couleurssdutot
 
JavaZone 2014 - goto java;
JavaZone 2014 - goto java;JavaZone 2014 - goto java;
JavaZone 2014 - goto java;
Martin (高馬丁) Skarsaune
 
Smoke and mirrors by neil gaiman
Smoke and mirrors   by neil gaimanSmoke and mirrors   by neil gaiman
Smoke and mirrors by neil gaiman
Naman 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 finale
Patrick Joubert
 
Bring your calculations to Scala!
Bring your calculations to Scala!Bring your calculations to Scala!
Bring your calculations to Scala!
Martin (高馬丁) Skarsaune
 
Rec101
Rec101Rec101
Goto devoxx
Goto devoxxGoto devoxx
2015.0508創新創業這條路
2015.0508創新創業這條路2015.0508創新創業這條路
2015.0508創新創業這條路Andy Peng
 
Smartek Industrial Automation
Smartek Industrial Automation Smartek Industrial Automation
Smartek Industrial Automation
elementFX The Ad Agency
 
2015.0508創新創業這條路2
2015.0508創新創業這條路22015.0508創新創業這條路2
2015.0508創新創業這條路2
Andy 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 Know
jxyz
 
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
Henryk 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 Construction
jxyz
 
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
Evan Chan
 

Viewers also liked (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 to 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 RxJava
Rick Warren
 
Java with a Clojure mindset
Java with a Clojure mindsetJava with a Clojure mindset
Java with a Clojure mindset
Daniel 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 extension
LINE Corporation
 
Curator intro
Curator introCurator intro
Curator intro
Jordan Zimmerman
 
Reactor spring one2gx_2013_0902-final
Reactor spring one2gx_2013_0902-finalReactor spring one2gx_2013_0902-final
Reactor spring one2gx_2013_0902-final
Sté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 @ LambdaDays
Manuel Bernhardt
 
Deferred Gratification
Deferred GratificationDeferred Gratification
Deferred Gratification
Terry Jones
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on Android
Tomáš Kypta
 
Implementing a JavaScript Engine
Implementing a JavaScript EngineImplementing a JavaScript Engine
Implementing a JavaScript Engine
Kris Mok
 
Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014
Jaroslaw 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 happy
Iordanis (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 experience
jazoon13
 
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 DIC
Konstantin 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 Pi
InfluxData
 
Douglas Crockford: Serversideness
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: Serversideness
WebExpo
 

Similar to 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
 

More from Martin (高馬丁) Skarsaune

jmc-devoxx.pptx
jmc-devoxx.pptxjmc-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
Martin (高馬丁) Skarsaune
 
Cloud Collaboration with Eclipse Che
Cloud Collaboration with Eclipse CheCloud Collaboration with Eclipse Che
Cloud Collaboration with Eclipse Che
Martin (高馬丁) Skarsaune
 
CodeOne Java Debugging Tips
CodeOne Java Debugging TipsCodeOne Java Debugging Tips
CodeOne Java Debugging Tips
Martin (高馬丁) Skarsaune
 
Java Debugging Tips @oredev
Java Debugging Tips @oredevJava Debugging Tips @oredev
Java Debugging Tips @oredev
Martin (高馬丁) Skarsaune
 
goto java; (Jfokus)
goto java; (Jfokus)goto java; (Jfokus)
goto java; (Jfokus)
Martin (高馬丁) Skarsaune
 
Tricks
TricksTricks
Small Lambda Talk @Booster2015
Small Lambda Talk @Booster2015Small Lambda Talk @Booster2015
Small Lambda Talk @Booster2015
Martin (高馬丁) Skarsaune
 

More from 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
 

Recently uploaded

Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
Donna Lenk
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
Pro Unity Game Development with C-sharp Book
Pro Unity Game Development with C-sharp BookPro Unity Game Development with C-sharp Book
Pro Unity Game Development with C-sharp Book
abdulrafaychaudhry
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
e20449
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Mind IT Systems
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
informapgpstrackings
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
Enterprise Software Development with No Code Solutions.pptx
Enterprise Software Development with No Code Solutions.pptxEnterprise Software Development with No Code Solutions.pptx
Enterprise Software Development with No Code Solutions.pptx
QuickwayInfoSystems3
 

Recently uploaded (20)

Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
Pro Unity Game Development with C-sharp Book
Pro Unity Game Development with C-sharp BookPro Unity Game Development with C-sharp Book
Pro Unity Game Development with C-sharp Book
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
Enterprise Software Development with No Code Solutions.pptx
Enterprise Software Development with No Code Solutions.pptxEnterprise Software Development with No Code Solutions.pptx
Enterprise Software Development with No Code Solutions.pptx
 

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

Editor's Notes

  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