SlideShare ist ein Scribd-Unternehmen logo
1 von 20
Downloaden Sie, um offline zu lesen
Streams and Lambdas – The Good, The Bad and the Ugly 
Peter Lawrey 
Higher Frequency Trading Ltd
Introduction 
For the last 6 months, Higher Frequency Trading has been 
porting a legacy C# application with over 25K lines of code 
to Java. 
We have translated many LINQ statements into Java 8 
Stream + Lambda. 
What are some common patterns and anti-patterns we 
have seen?
Contains 2.0 
if (list.stream().anyMatch(p -> p.getType() == Type.Cash)) {
Deep Copy 
List<Position> newPositions = classPos.stream() 
.map(Position::clone) 
.collect(toList())
Validate all entries 
positions.forEach(Position::validate); 
Validate throws an InvalidStateException if invalid
Summing BigDecimal 
BigDecimal sum = getResults().stream() 
.reduce(BigDecimal.ZERO, 
(bd, t) -> bd.add(t.getRequirement()), 
BigDecimal::add);
Sorting by multiple fields 
setTrades(getTrades().stream() 
.sorted(comparing(t -> t.getInfo().getDate()) 
.thenComparing(Position::getCUSIP) 
.thenComparing(Position::getQuantity).reversed()) 
.collect(Collectors.toList()));
Group By 
Map<String, List<Position>> positionBySymbol = 
positions.values().stream() 
.filter(p -> p.getQuantity() != 0) 
.collect(groupingBy(Position::getSymbol));
Streaming Maps 
pos.entrySet().stream() 
.filter(p -> p.getValue().getQuantity() != 0.0) 
.forEach(p -> pos2.put(p.getKey(), p.getValue()));
To collect or not (anti-pattern) 
getTrades().stream() 
.filter(t -> getDate().equals(t.getInfo().getDate())) 
.collect(toList()) 
.forEach(t -> trades.add(t.getInfo()));
To collect or not (solution) 
List<Trade> trades = getTrades().stream() 
.filter(t -> getDate().equals(t.getInfo().getDate())) 
.map(t → t.getInfo()) 
.collect(Collectors.toList());
Sort of sorted (anti pattern) 
Map<Date, List<Trade>> groupTrades = 
trades.stream() 
.sorted(comparing(Trade::getDate)) 
.collect(groupingBy(Trade::getDate));
Sort of sorted (solution) 
Map<Date, List<Trade>> groupTrades = 
trades.stream() 
.collect(groupingBy( 
TradeDetail::getTradeDate, 
TreeMap::new, 
toList()));
Multi-sorted (anti-pattern) 
return trade.stream() 
.filter(t -> !isExcluded(t)) 
.sorted(comparing(Trade::getDate)) 
.sorted(comparing(Trade::getCUSIP)) 
.sorted(comparing(Trade::getNetAmount)) 
.collect(toList());
Multi-sorted (solution) 
return trade.stream() 
.filter(t -> !isExcluded(t)) 
.sorted(comparing(Trade::getNetAmount) 
.thenComparing(Trade::getCUSIP) 
.thenComparing(Trade::getDate)) 
.collect(toList());
Top twenty words (Ugly) 
List<String> words = 
Files.lines(path).parallel() 
.flatMap(line -> Arrays.asList(line.split("b")).stream()) 
.collect(groupingBy(w -> w, counting())) 
.entrySet().stream() 
.sorted(comparing(Map.Entry<String, Long>::getValue).reversed()) 
.limit(20) 
.map(Map.Entry::getKey) 
.collect(Collectors.toList());
I must use streams (Ugly) 
combinedList.addAll( 
balances.stream().collect(Collectors.toList())); 
List<Trade> allTrades = new ArrayList<>(); 
trades1.forEach(t -> allTrades.add(t)); 
trades2.forEach(t -> allTrades.add(t));
Optional denial 
Position todayPos = newPos.stream() 
.filter(pos -> pos.getCUSIP().equals(p.getCUSIP())) 
.findFirst().orElse(null); 
if (todayPos != null) {
Optional denial 
Optional<MTrade> otodayTrade = trades.stream() 
.filter(t -> t.getCUSIP().equals(p.getCUSIP())).findFirst(); 
MTrade todayTrade = null; 
if (otodayTrade.isPresent()) todayTrade = otodayTrade.get(); 
if (todayTrade != null && todayTrade.getClosingPrice() != null) {
Q & A 
Peter Lawrey 
http://vanillajava.blogspot.com/ 
@PeterLawrey 
peter.lawrey@higherfrequencytrading.com

Weitere ähnliche Inhalte

Was ist angesagt?

Csc1100 lecture07 ch07_pt1-1
Csc1100 lecture07 ch07_pt1-1Csc1100 lecture07 ch07_pt1-1
Csc1100 lecture07 ch07_pt1-1IIUM
 
The Ring programming language version 1.3 book - Part 25 of 88
The Ring programming language version 1.3 book - Part 25 of 88The Ring programming language version 1.3 book - Part 25 of 88
The Ring programming language version 1.3 book - Part 25 of 88Mahmoud Samir Fayed
 
C programming array & shorting
C  programming array & shortingC  programming array & shorting
C programming array & shortingargusacademy
 
Cocoaheads Meetup / Alex Zimin / Swift magic
Cocoaheads Meetup / Alex Zimin / Swift magicCocoaheads Meetup / Alex Zimin / Swift magic
Cocoaheads Meetup / Alex Zimin / Swift magicBadoo Development
 
Generic Functional Programming with Type Classes
Generic Functional Programming with Type ClassesGeneric Functional Programming with Type Classes
Generic Functional Programming with Type ClassesTapio Rautonen
 
Scala collection methods flatMap and flatten are more powerful than monadic f...
Scala collection methods flatMap and flatten are more powerful than monadic f...Scala collection methods flatMap and flatten are more powerful than monadic f...
Scala collection methods flatMap and flatten are more powerful than monadic f...Philip Schwarz
 
Pandas pythonfordatascience
Pandas pythonfordatasciencePandas pythonfordatascience
Pandas pythonfordatascienceNishant Upadhyay
 
Java8 stream
Java8 streamJava8 stream
Java8 streamkoji lin
 
Nu program language on Shibuya.lisp#5 LT
Nu program language on  Shibuya.lisp#5 LTNu program language on  Shibuya.lisp#5 LT
Nu program language on Shibuya.lisp#5 LTYuumi Yoshida
 
SupportVectorRegression
SupportVectorRegressionSupportVectorRegression
SupportVectorRegressionDaniel K
 
Templates in C++
Templates in C++Templates in C++
Templates in C++Tech_MX
 
support vector regression
support vector regressionsupport vector regression
support vector regressionAkhilesh Joshi
 
polynomial linear regression
polynomial linear regressionpolynomial linear regression
polynomial linear regressionAkhilesh Joshi
 
multiple linear regression
multiple linear regressionmultiple linear regression
multiple linear regressionAkhilesh Joshi
 
Simple IO Monad in 'Functional Programming in Scala'
Simple IO Monad in 'Functional Programming in Scala'Simple IO Monad in 'Functional Programming in Scala'
Simple IO Monad in 'Functional Programming in Scala'Philip Schwarz
 
random forest regression
random forest regressionrandom forest regression
random forest regressionAkhilesh Joshi
 

Was ist angesagt? (20)

Csc1100 lecture07 ch07_pt1-1
Csc1100 lecture07 ch07_pt1-1Csc1100 lecture07 ch07_pt1-1
Csc1100 lecture07 ch07_pt1-1
 
The Ring programming language version 1.3 book - Part 25 of 88
The Ring programming language version 1.3 book - Part 25 of 88The Ring programming language version 1.3 book - Part 25 of 88
The Ring programming language version 1.3 book - Part 25 of 88
 
C programming array & shorting
C  programming array & shortingC  programming array & shorting
C programming array & shorting
 
Cocoaheads Meetup / Alex Zimin / Swift magic
Cocoaheads Meetup / Alex Zimin / Swift magicCocoaheads Meetup / Alex Zimin / Swift magic
Cocoaheads Meetup / Alex Zimin / Swift magic
 
Generic Functional Programming with Type Classes
Generic Functional Programming with Type ClassesGeneric Functional Programming with Type Classes
Generic Functional Programming with Type Classes
 
Scala collection methods flatMap and flatten are more powerful than monadic f...
Scala collection methods flatMap and flatten are more powerful than monadic f...Scala collection methods flatMap and flatten are more powerful than monadic f...
Scala collection methods flatMap and flatten are more powerful than monadic f...
 
Pandas pythonfordatascience
Pandas pythonfordatasciencePandas pythonfordatascience
Pandas pythonfordatascience
 
Apache spark
Apache sparkApache spark
Apache spark
 
Java8 stream
Java8 streamJava8 stream
Java8 stream
 
Nu program language on Shibuya.lisp#5 LT
Nu program language on  Shibuya.lisp#5 LTNu program language on  Shibuya.lisp#5 LT
Nu program language on Shibuya.lisp#5 LT
 
SupportVectorRegression
SupportVectorRegressionSupportVectorRegression
SupportVectorRegression
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
 
Scala Higher Order Functions
Scala Higher Order FunctionsScala Higher Order Functions
Scala Higher Order Functions
 
support vector regression
support vector regressionsupport vector regression
support vector regression
 
Vim Registers
Vim RegistersVim Registers
Vim Registers
 
polynomial linear regression
polynomial linear regressionpolynomial linear regression
polynomial linear regression
 
multiple linear regression
multiple linear regressionmultiple linear regression
multiple linear regression
 
Struct examples
Struct examplesStruct examples
Struct examples
 
Simple IO Monad in 'Functional Programming in Scala'
Simple IO Monad in 'Functional Programming in Scala'Simple IO Monad in 'Functional Programming in Scala'
Simple IO Monad in 'Functional Programming in Scala'
 
random forest regression
random forest regressionrandom forest regression
random forest regression
 

Andere mochten auch

Deterministic behaviour and performance in trading systems
Deterministic behaviour and performance in trading systemsDeterministic behaviour and performance in trading systems
Deterministic behaviour and performance in trading systemsPeter Lawrey
 
Low latency for high throughput
Low latency for high throughputLow latency for high throughput
Low latency for high throughputPeter Lawrey
 
Responding rapidly when you have 100+ GB data sets in Java
Responding rapidly when you have 100+ GB data sets in JavaResponding rapidly when you have 100+ GB data sets in Java
Responding rapidly when you have 100+ GB data sets in JavaPeter Lawrey
 
Determinism in finance
Determinism in financeDeterminism in finance
Determinism in financePeter Lawrey
 
Low level java programming
Low level java programmingLow level java programming
Low level java programmingPeter Lawrey
 
Low latency microservices in java QCon New York 2016
Low latency microservices in java   QCon New York 2016Low latency microservices in java   QCon New York 2016
Low latency microservices in java QCon New York 2016Peter Lawrey
 
High Frequency Trading and NoSQL database
High Frequency Trading and NoSQL databaseHigh Frequency Trading and NoSQL database
High Frequency Trading and NoSQL databasePeter Lawrey
 
Low latency in java 8 v5
Low latency in java 8 v5Low latency in java 8 v5
Low latency in java 8 v5Peter Lawrey
 
Microservices for performance - GOTO Chicago 2016
Microservices for performance - GOTO Chicago 2016Microservices for performance - GOTO Chicago 2016
Microservices for performance - GOTO Chicago 2016Peter Lawrey
 
Introduction to OpenHFT for Melbourne Java Users Group
Introduction to OpenHFT for Melbourne Java Users GroupIntroduction to OpenHFT for Melbourne Java Users Group
Introduction to OpenHFT for Melbourne Java Users GroupPeter Lawrey
 
Reactive programming with examples
Reactive programming with examplesReactive programming with examples
Reactive programming with examplesPeter Lawrey
 
Advanced off heap ipc
Advanced off heap ipcAdvanced off heap ipc
Advanced off heap ipcPeter Lawrey
 
Open HFT libraries in @Java
Open HFT libraries in @JavaOpen HFT libraries in @Java
Open HFT libraries in @JavaPeter Lawrey
 
Thread Safe Interprocess Shared Memory in Java (in 7 mins)
Thread Safe Interprocess Shared Memory in Java (in 7 mins)Thread Safe Interprocess Shared Memory in Java (in 7 mins)
Thread Safe Interprocess Shared Memory in Java (in 7 mins)Peter Lawrey
 
GC free coding in @Java presented @Geecon
GC free coding in @Java presented @GeeconGC free coding in @Java presented @Geecon
GC free coding in @Java presented @GeeconPeter Lawrey
 
Big Data for Finance – Challenges in High-Frequency Trading
Big Data for Finance – Challenges in High-Frequency TradingBig Data for Finance – Challenges in High-Frequency Trading
Big Data for Finance – Challenges in High-Frequency TradingThink Big, a Teradata Company
 

Andere mochten auch (16)

Deterministic behaviour and performance in trading systems
Deterministic behaviour and performance in trading systemsDeterministic behaviour and performance in trading systems
Deterministic behaviour and performance in trading systems
 
Low latency for high throughput
Low latency for high throughputLow latency for high throughput
Low latency for high throughput
 
Responding rapidly when you have 100+ GB data sets in Java
Responding rapidly when you have 100+ GB data sets in JavaResponding rapidly when you have 100+ GB data sets in Java
Responding rapidly when you have 100+ GB data sets in Java
 
Determinism in finance
Determinism in financeDeterminism in finance
Determinism in finance
 
Low level java programming
Low level java programmingLow level java programming
Low level java programming
 
Low latency microservices in java QCon New York 2016
Low latency microservices in java   QCon New York 2016Low latency microservices in java   QCon New York 2016
Low latency microservices in java QCon New York 2016
 
High Frequency Trading and NoSQL database
High Frequency Trading and NoSQL databaseHigh Frequency Trading and NoSQL database
High Frequency Trading and NoSQL database
 
Low latency in java 8 v5
Low latency in java 8 v5Low latency in java 8 v5
Low latency in java 8 v5
 
Microservices for performance - GOTO Chicago 2016
Microservices for performance - GOTO Chicago 2016Microservices for performance - GOTO Chicago 2016
Microservices for performance - GOTO Chicago 2016
 
Introduction to OpenHFT for Melbourne Java Users Group
Introduction to OpenHFT for Melbourne Java Users GroupIntroduction to OpenHFT for Melbourne Java Users Group
Introduction to OpenHFT for Melbourne Java Users Group
 
Reactive programming with examples
Reactive programming with examplesReactive programming with examples
Reactive programming with examples
 
Advanced off heap ipc
Advanced off heap ipcAdvanced off heap ipc
Advanced off heap ipc
 
Open HFT libraries in @Java
Open HFT libraries in @JavaOpen HFT libraries in @Java
Open HFT libraries in @Java
 
Thread Safe Interprocess Shared Memory in Java (in 7 mins)
Thread Safe Interprocess Shared Memory in Java (in 7 mins)Thread Safe Interprocess Shared Memory in Java (in 7 mins)
Thread Safe Interprocess Shared Memory in Java (in 7 mins)
 
GC free coding in @Java presented @Geecon
GC free coding in @Java presented @GeeconGC free coding in @Java presented @Geecon
GC free coding in @Java presented @Geecon
 
Big Data for Finance – Challenges in High-Frequency Trading
Big Data for Finance – Challenges in High-Frequency TradingBig Data for Finance – Challenges in High-Frequency Trading
Big Data for Finance – Challenges in High-Frequency Trading
 

Ähnlich wie Streams and lambdas the good, the bad and the ugly

Big Data Analytics with Scala at SCALA.IO 2013
Big Data Analytics with Scala at SCALA.IO 2013Big Data Analytics with Scala at SCALA.IO 2013
Big Data Analytics with Scala at SCALA.IO 2013Samir Bessalah
 
Spring data access
Spring data accessSpring data access
Spring data access명철 강
 
User Defined Aggregation in Apache Spark: A Love Story
User Defined Aggregation in Apache Spark: A Love StoryUser Defined Aggregation in Apache Spark: A Love Story
User Defined Aggregation in Apache Spark: A Love StoryDatabricks
 
User Defined Aggregation in Apache Spark: A Love Story
User Defined Aggregation in Apache Spark: A Love StoryUser Defined Aggregation in Apache Spark: A Love Story
User Defined Aggregation in Apache Spark: A Love StoryDatabricks
 
Java Foundations: Maps, Lambda and Stream API
Java Foundations: Maps, Lambda and Stream APIJava Foundations: Maps, Lambda and Stream API
Java Foundations: Maps, Lambda and Stream APISvetlin Nakov
 
No more loops with lambdaj
No more loops with lambdajNo more loops with lambdaj
No more loops with lambdajMario Fusco
 
Java 8, lambdas, generics: How to survive? - NYC Java Meetup Group
Java 8, lambdas, generics: How to survive? - NYC Java Meetup GroupJava 8, lambdas, generics: How to survive? - NYC Java Meetup Group
Java 8, lambdas, generics: How to survive? - NYC Java Meetup GroupHenri Tremblay
 
The Time to Defer is Now
The Time to Defer is NowThe Time to Defer is Now
The Time to Defer is NowMichael Diamant
 
Stata cheat sheet: data processing
Stata cheat sheet: data processingStata cheat sheet: data processing
Stata cheat sheet: data processingTim Essam
 
Practical scalaz
Practical scalazPractical scalaz
Practical scalazoxbow_lakes
 
Martin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick ReferenceMartin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick ReferenceSeung-Bum Lee
 
Writing beautiful code with Java 8
Writing beautiful code with Java 8Writing beautiful code with Java 8
Writing beautiful code with Java 8Sergiu Mircea Indrie
 
Generics and Lambdas cocktail explained - Montreal JUG
Generics and Lambdas cocktail explained  - Montreal JUGGenerics and Lambdas cocktail explained  - Montreal JUG
Generics and Lambdas cocktail explained - Montreal JUGHenri Tremblay
 
Dependency Injection in Scala - Beyond the Cake Pattern
Dependency Injection in Scala - Beyond the Cake PatternDependency Injection in Scala - Beyond the Cake Pattern
Dependency Injection in Scala - Beyond the Cake PatternDebasish Ghosh
 
Java8: Language Enhancements
Java8: Language EnhancementsJava8: Language Enhancements
Java8: Language EnhancementsYuriy Bondaruk
 
Stratosphere Intro (Java and Scala Interface)
Stratosphere Intro (Java and Scala Interface)Stratosphere Intro (Java and Scala Interface)
Stratosphere Intro (Java and Scala Interface)Robert Metzger
 

Ähnlich wie Streams and lambdas the good, the bad and the ugly (20)

Big Data Analytics with Scala at SCALA.IO 2013
Big Data Analytics with Scala at SCALA.IO 2013Big Data Analytics with Scala at SCALA.IO 2013
Big Data Analytics with Scala at SCALA.IO 2013
 
Spring data access
Spring data accessSpring data access
Spring data access
 
Spark workshop
Spark workshopSpark workshop
Spark workshop
 
User Defined Aggregation in Apache Spark: A Love Story
User Defined Aggregation in Apache Spark: A Love StoryUser Defined Aggregation in Apache Spark: A Love Story
User Defined Aggregation in Apache Spark: A Love Story
 
User Defined Aggregation in Apache Spark: A Love Story
User Defined Aggregation in Apache Spark: A Love StoryUser Defined Aggregation in Apache Spark: A Love Story
User Defined Aggregation in Apache Spark: A Love Story
 
Java Foundations: Maps, Lambda and Stream API
Java Foundations: Maps, Lambda and Stream APIJava Foundations: Maps, Lambda and Stream API
Java Foundations: Maps, Lambda and Stream API
 
R console
R consoleR console
R console
 
Vaadin+Scala
Vaadin+ScalaVaadin+Scala
Vaadin+Scala
 
No more loops with lambdaj
No more loops with lambdajNo more loops with lambdaj
No more loops with lambdaj
 
Java 8, lambdas, generics: How to survive? - NYC Java Meetup Group
Java 8, lambdas, generics: How to survive? - NYC Java Meetup GroupJava 8, lambdas, generics: How to survive? - NYC Java Meetup Group
Java 8, lambdas, generics: How to survive? - NYC Java Meetup Group
 
The Time to Defer is Now
The Time to Defer is NowThe Time to Defer is Now
The Time to Defer is Now
 
Stata cheat sheet: data processing
Stata cheat sheet: data processingStata cheat sheet: data processing
Stata cheat sheet: data processing
 
Practical scalaz
Practical scalazPractical scalaz
Practical scalaz
 
Martin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick ReferenceMartin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick Reference
 
Writing beautiful code with Java 8
Writing beautiful code with Java 8Writing beautiful code with Java 8
Writing beautiful code with Java 8
 
Generics and Lambdas cocktail explained - Montreal JUG
Generics and Lambdas cocktail explained  - Montreal JUGGenerics and Lambdas cocktail explained  - Montreal JUG
Generics and Lambdas cocktail explained - Montreal JUG
 
Dependency Injection in Scala - Beyond the Cake Pattern
Dependency Injection in Scala - Beyond the Cake PatternDependency Injection in Scala - Beyond the Cake Pattern
Dependency Injection in Scala - Beyond the Cake Pattern
 
Introduction to Redux
Introduction to ReduxIntroduction to Redux
Introduction to Redux
 
Java8: Language Enhancements
Java8: Language EnhancementsJava8: Language Enhancements
Java8: Language Enhancements
 
Stratosphere Intro (Java and Scala Interface)
Stratosphere Intro (Java and Scala Interface)Stratosphere Intro (Java and Scala Interface)
Stratosphere Intro (Java and Scala Interface)
 

Kürzlich hochgeladen

A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Landscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfLandscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfAarwolf Industries LLC
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
Kuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorialKuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorialJoão Esperancinha
 
Accelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessAccelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessWSO2
 
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...Jeffrey Haguewood
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkPixlogix Infotech
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integrationmarketing932765
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...Nikki Chapple
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
Irene Moetsana-Moeng: Stakeholders in Cybersecurity: Collaborative Defence fo...
Irene Moetsana-Moeng: Stakeholders in Cybersecurity: Collaborative Defence fo...Irene Moetsana-Moeng: Stakeholders in Cybersecurity: Collaborative Defence fo...
Irene Moetsana-Moeng: Stakeholders in Cybersecurity: Collaborative Defence fo...itnewsafrica
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#Karmanjay Verma
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...itnewsafrica
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
A Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxA Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxAna-Maria Mihalceanu
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesBernd Ruecker
 

Kürzlich hochgeladen (20)

A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Landscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfLandscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdf
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
Kuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorialKuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorial
 
Accelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessAccelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with Platformless
 
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App Framework
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
Irene Moetsana-Moeng: Stakeholders in Cybersecurity: Collaborative Defence fo...
Irene Moetsana-Moeng: Stakeholders in Cybersecurity: Collaborative Defence fo...Irene Moetsana-Moeng: Stakeholders in Cybersecurity: Collaborative Defence fo...
Irene Moetsana-Moeng: Stakeholders in Cybersecurity: Collaborative Defence fo...
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
A Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxA Glance At The Java Performance Toolbox
A Glance At The Java Performance Toolbox
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architectures
 

Streams and lambdas the good, the bad and the ugly

  • 1. Streams and Lambdas – The Good, The Bad and the Ugly Peter Lawrey Higher Frequency Trading Ltd
  • 2. Introduction For the last 6 months, Higher Frequency Trading has been porting a legacy C# application with over 25K lines of code to Java. We have translated many LINQ statements into Java 8 Stream + Lambda. What are some common patterns and anti-patterns we have seen?
  • 3. Contains 2.0 if (list.stream().anyMatch(p -> p.getType() == Type.Cash)) {
  • 4. Deep Copy List<Position> newPositions = classPos.stream() .map(Position::clone) .collect(toList())
  • 5. Validate all entries positions.forEach(Position::validate); Validate throws an InvalidStateException if invalid
  • 6. Summing BigDecimal BigDecimal sum = getResults().stream() .reduce(BigDecimal.ZERO, (bd, t) -> bd.add(t.getRequirement()), BigDecimal::add);
  • 7. Sorting by multiple fields setTrades(getTrades().stream() .sorted(comparing(t -> t.getInfo().getDate()) .thenComparing(Position::getCUSIP) .thenComparing(Position::getQuantity).reversed()) .collect(Collectors.toList()));
  • 8. Group By Map<String, List<Position>> positionBySymbol = positions.values().stream() .filter(p -> p.getQuantity() != 0) .collect(groupingBy(Position::getSymbol));
  • 9. Streaming Maps pos.entrySet().stream() .filter(p -> p.getValue().getQuantity() != 0.0) .forEach(p -> pos2.put(p.getKey(), p.getValue()));
  • 10. To collect or not (anti-pattern) getTrades().stream() .filter(t -> getDate().equals(t.getInfo().getDate())) .collect(toList()) .forEach(t -> trades.add(t.getInfo()));
  • 11. To collect or not (solution) List<Trade> trades = getTrades().stream() .filter(t -> getDate().equals(t.getInfo().getDate())) .map(t → t.getInfo()) .collect(Collectors.toList());
  • 12. Sort of sorted (anti pattern) Map<Date, List<Trade>> groupTrades = trades.stream() .sorted(comparing(Trade::getDate)) .collect(groupingBy(Trade::getDate));
  • 13. Sort of sorted (solution) Map<Date, List<Trade>> groupTrades = trades.stream() .collect(groupingBy( TradeDetail::getTradeDate, TreeMap::new, toList()));
  • 14. Multi-sorted (anti-pattern) return trade.stream() .filter(t -> !isExcluded(t)) .sorted(comparing(Trade::getDate)) .sorted(comparing(Trade::getCUSIP)) .sorted(comparing(Trade::getNetAmount)) .collect(toList());
  • 15. Multi-sorted (solution) return trade.stream() .filter(t -> !isExcluded(t)) .sorted(comparing(Trade::getNetAmount) .thenComparing(Trade::getCUSIP) .thenComparing(Trade::getDate)) .collect(toList());
  • 16. Top twenty words (Ugly) List<String> words = Files.lines(path).parallel() .flatMap(line -> Arrays.asList(line.split("b")).stream()) .collect(groupingBy(w -> w, counting())) .entrySet().stream() .sorted(comparing(Map.Entry<String, Long>::getValue).reversed()) .limit(20) .map(Map.Entry::getKey) .collect(Collectors.toList());
  • 17. I must use streams (Ugly) combinedList.addAll( balances.stream().collect(Collectors.toList())); List<Trade> allTrades = new ArrayList<>(); trades1.forEach(t -> allTrades.add(t)); trades2.forEach(t -> allTrades.add(t));
  • 18. Optional denial Position todayPos = newPos.stream() .filter(pos -> pos.getCUSIP().equals(p.getCUSIP())) .findFirst().orElse(null); if (todayPos != null) {
  • 19. Optional denial Optional<MTrade> otodayTrade = trades.stream() .filter(t -> t.getCUSIP().equals(p.getCUSIP())).findFirst(); MTrade todayTrade = null; if (otodayTrade.isPresent()) todayTrade = otodayTrade.get(); if (todayTrade != null && todayTrade.getClosingPrice() != null) {
  • 20. Q & A Peter Lawrey http://vanillajava.blogspot.com/ @PeterLawrey peter.lawrey@higherfrequencytrading.com