SlideShare una empresa de Scribd logo
1 de 35
Javaland 2015
Peter Lawrey
Legacy Lambda Code in Java
Agenda
• Lambdas: A complicated way to do something simple?
• Lambda Patterns we used.
• Lambda Patterns we shouldn’t have used.
• Lambda Patterns we have used since.
Counting elements in a Stream
long count = list.stream().count();
Counting elements in a Stream
long count = list.stream().count();
// Stream.count()
@Override
public final long count() {
return mapToLong(e -> 1L).sum();
}
Counting elements in a Stream
long count = list.stream().count();
// LongStream.sum()
@Override
public final long sum() {
// use better algorithm to compensate for
intermediate overflow?
return reduce(0, Long::sum);
}
Counting elements in a Stream
long count = list.parallelStream().count();
When the examples get more complex, lambdas become much
more interesting.
Porting a legacy C# application
For the last 8 months, Higher Frequency Trading ported 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?
Summing BigDecimal
getResults().stream()
.reduce(BigDecimal.ZERO,
(bd, t) -> bd.add(t.getRequirement()),
BigDecimal::add);
Validate all entries
positions.stream().forEach(Position::validate);
Validate throws an exception.
Sorting by multiple fields.
setTrades(trades.stream()
.sorted(comparing(t -> t.getInfo().getDate())
.thenComparing(Position::getCUSIP)
.thenComparing(Position::getQuantity)
.reversed())
.collect(toList()));
Sorting by multiple fields,
Quantity reversed
setTrades(trades.stream()
.sorted(comparing(t -> t.getInfo().getDate())
.thenComparing(Position::getCUSIP)
.reversed()
.thenComparing(Position::getQuantity)
.reversed())
.collect(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()));
Contains 2.0
if (list.stream()
.anyMatch(p -> p.getType() == Type.Cash)) {
Deep copy
List<Position> newPositions =
classPos.stream()
.map(Position::clone)
.collect(toList())
To collect or not to collect
(anti-pattern)
getTrades().stream()
.filter(t -> getDate().equals(t.getInfo().getDate()))
.collect(toList())
.forEach(t -> trades.add(t.getInfo()));
To collect or not to collect
(solution)
List<TradeInfo> trades =
getTrades().stream()
.filter(t -> getDate().equals(
t.getInfo().getDate()))
.map(Trade::getInfo)
.collect(toList());
Sort of sorted (anti-pattern)
Map<Date, List<Trade>> groupTrades = trades.stream()
.sorted(comparing(Trade::getDate))
.collect(groupingBy(Trade::getDate));
Sorting (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());
See slide 2 example for solution.
Concurrent removal
? anti-pattern ?
input.stream()
.filter(t -> t.getParent() == p.getParent())
.forEach(input::remove);
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){
Optional for equals
public boolean equals(Object obj) {
return Optional.ofNullable(obj)
.filter(that -> that instanceof Test)
.map(that -> (Test)that)
.filter(that -> Objects.equals(this.s1, that.s1))
.filter(that -> Objects.equals(this.s2, that.s2))
.isPresent();
}
Posted by Marko Topolnik
Find the twenty most frequent words in a file
To use parallel or not?
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());
Lambdas and templates (before Java 8)
long value;
this.lock.lock();
try {
value = doSomething();
} finally {
this.lock.unlock();
}
Lambdas and templates (with Java 8)
public static <R> R with(Lock lock, Callable<R> work) {
lock.lock();
try {
return work.call();
} finally {
lock.unlock();
}
}
Lambdas and templates (with Java 8)
long value = with(lock, this::doSomething);
Note: with inlining, the temporary “Long” object can be eliminated.
Lambdas and performance
public void readMarshallable(Wire wire) {
wire.read(Fields.I).int32(x -> i = x)
.read(Fields.J).int32(x -> j = x)
.read(Fields.K).int32(x -> k = x)
.read(Fields.L).int32(x -> l = x)
.read(Fields.M).int32(x -> m = x)
.read(Fields.N).int32(x -> n = x)
.read(Fields.O).int32(x -> o = x)
.read(Fields.P).int32(x -> p = x);
}
Lambdas and performance
garbage in bytes per lambda
Lambdas and performance
-XX:BCEATraceLevel=3
Prints messages like
Skipping method because: code size (271) exceeds
MaxBCEAEstimateSize (150).
So I raised the
-XX:MaxBCEAEstimateSize=300
Lambda type inference
• Java 8 uses type inference much more than before.
• Inference can appear to be as a cast.
// error type is not known.
Object o = () -> System.out::println;
// type is inferred.
Runnable o = () -> System.out::println;
// type is inferred not cast at runtime.
Object o = (Runnable & Serializable)
() -> System.out::println;
Lambda internals
• Classes for Lambdas are generated at runtime.
lambda.getClass() still works.
• The contents of code in a lambda is added as a static method,
except …
• When a lambda expression refers to a method e.g.
this::method or Class::new no additional method is created.
• Provided your code is inlined, the lambda “object” can be
eliminated. This also works for anonymous inner classes.
End randomly (Don’t try this at home)
IntStream.range(0, 128).parallel()
.forEach(System::exit);
Q & A
http://vanillajava.blogspot.com/
Peter Lawrey
@PeterLawrey

Más contenido relacionado

La actualidad más candente

Csc1100 lecture07 ch07_pt1-1
Csc1100 lecture07 ch07_pt1-1Csc1100 lecture07 ch07_pt1-1
Csc1100 lecture07 ch07_pt1-1
IIUM
 
Java8 stream
Java8 streamJava8 stream
Java8 stream
koji lin
 
SupportVectorRegression
SupportVectorRegressionSupportVectorRegression
SupportVectorRegression
Daniel K
 

La actualidad más candente (20)

Csc1100 lecture07 ch07_pt1-1
Csc1100 lecture07 ch07_pt1-1Csc1100 lecture07 ch07_pt1-1
Csc1100 lecture07 ch07_pt1-1
 
Cocoaheads Meetup / Alex Zimin / Swift magic
Cocoaheads Meetup / Alex Zimin / Swift magicCocoaheads Meetup / Alex Zimin / Swift magic
Cocoaheads Meetup / Alex Zimin / Swift magic
 
C programming array & shorting
C  programming array & shortingC  programming array & shorting
C programming array & shorting
 
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
 
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...
 
Java8 stream
Java8 streamJava8 stream
Java8 stream
 
Pandas pythonfordatascience
Pandas pythonfordatasciencePandas pythonfordatascience
Pandas pythonfordatascience
 
Essence of the iterator pattern
Essence of the iterator patternEssence of the iterator pattern
Essence of the iterator pattern
 
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
 
Apache spark
Apache sparkApache spark
Apache spark
 
The Ring programming language version 1.5.2 book - Part 21 of 181
The Ring programming language version 1.5.2 book - Part 21 of 181The Ring programming language version 1.5.2 book - Part 21 of 181
The Ring programming language version 1.5.2 book - Part 21 of 181
 
Scala Higher Order Functions
Scala Higher Order FunctionsScala Higher Order Functions
Scala Higher Order Functions
 
Vim Registers
Vim RegistersVim Registers
Vim Registers
 
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'
 
support vector regression
support vector regressionsupport vector regression
support vector regression
 
SupportVectorRegression
SupportVectorRegressionSupportVectorRegression
SupportVectorRegression
 
multiple linear regression
multiple linear regressionmultiple linear regression
multiple linear regression
 
polynomial linear regression
polynomial linear regressionpolynomial linear regression
polynomial linear regression
 
Hive function-cheat-sheet
Hive function-cheat-sheetHive function-cheat-sheet
Hive function-cheat-sheet
 

Destacado

Advanced off heap ipc
Advanced off heap ipcAdvanced off heap ipc
Advanced off heap ipc
Peter Lawrey
 

Destacado (20)

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
 
Stateless authentication for microservices applications - JavaLand 2015
Stateless authentication for microservices applications -  JavaLand 2015Stateless authentication for microservices applications -  JavaLand 2015
Stateless authentication for microservices applications - JavaLand 2015
 
NoSQL Riak MongoDB Elasticsearch - All The Same?
NoSQL Riak MongoDB Elasticsearch - All The Same?NoSQL Riak MongoDB Elasticsearch - All The Same?
NoSQL Riak MongoDB Elasticsearch - All The Same?
 
JavaLand - Integration Testing How-to
JavaLand - Integration Testing How-toJavaLand - Integration Testing How-to
JavaLand - Integration Testing How-to
 
Javaland keynote final
Javaland keynote finalJavaland keynote final
Javaland keynote final
 
Advanced off heap ipc
Advanced off heap ipcAdvanced off heap ipc
Advanced off heap ipc
 
Cassandra Troubleshooting (for 2.0 and earlier)
Cassandra Troubleshooting (for 2.0 and earlier)Cassandra Troubleshooting (for 2.0 and earlier)
Cassandra Troubleshooting (for 2.0 and earlier)
 
Cassandra 3.0 advanced preview
Cassandra 3.0 advanced previewCassandra 3.0 advanced preview
Cassandra 3.0 advanced preview
 
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)
 

Similar a Legacy lambda code

Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
Dmitry Buzdin
 

Similar a Legacy lambda code (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
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
 
Spark workshop
Spark workshopSpark workshop
Spark workshop
 
Lambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter LawreyLambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter Lawrey
 
Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQChapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQ
 
Practical cats
Practical catsPractical cats
Practical cats
 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
 
No more struggles with Apache Spark workloads in production
No more struggles with Apache Spark workloads in productionNo more struggles with Apache Spark workloads in production
No more struggles with Apache Spark workloads in production
 
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
 
Real Time Big Data Management
Real Time Big Data ManagementReal Time Big Data Management
Real Time Big Data Management
 
Stratosphere Intro (Java and Scala Interface)
Stratosphere Intro (Java and Scala Interface)Stratosphere Intro (Java and Scala Interface)
Stratosphere Intro (Java and Scala Interface)
 
Java 8
Java 8Java 8
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
 
C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
4 R Tutorial DPLYR Apply Function
4 R Tutorial DPLYR Apply Function4 R Tutorial DPLYR Apply Function
4 R Tutorial DPLYR Apply Function
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 
JBUG 11 - Scala For Java Programmers
JBUG 11 - Scala For Java ProgrammersJBUG 11 - Scala For Java Programmers
JBUG 11 - Scala For Java Programmers
 
bobok
bobokbobok
bobok
 

Más de Peter Lawrey (6)

Chronicle accelerate building a digital currency
Chronicle accelerate   building a digital currencyChronicle accelerate   building a digital currency
Chronicle accelerate building a digital currency
 
Chronicle Accelerate Crypto Investor conference
Chronicle Accelerate Crypto Investor conferenceChronicle Accelerate Crypto Investor conference
Chronicle Accelerate Crypto Investor conference
 
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
 
Using BigDecimal and double
Using BigDecimal and doubleUsing BigDecimal and double
Using BigDecimal and double
 
Introduction to chronicle (low latency persistence)
Introduction to chronicle (low latency persistence)Introduction to chronicle (low latency persistence)
Introduction to chronicle (low latency persistence)
 
Writing and testing high frequency trading engines in java
Writing and testing high frequency trading engines in javaWriting and testing high frequency trading engines in java
Writing and testing high frequency trading engines in java
 

Último

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Último (20)

Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 

Legacy lambda code

  • 1. Javaland 2015 Peter Lawrey Legacy Lambda Code in Java
  • 2. Agenda • Lambdas: A complicated way to do something simple? • Lambda Patterns we used. • Lambda Patterns we shouldn’t have used. • Lambda Patterns we have used since.
  • 3. Counting elements in a Stream long count = list.stream().count();
  • 4. Counting elements in a Stream long count = list.stream().count(); // Stream.count() @Override public final long count() { return mapToLong(e -> 1L).sum(); }
  • 5. Counting elements in a Stream long count = list.stream().count(); // LongStream.sum() @Override public final long sum() { // use better algorithm to compensate for intermediate overflow? return reduce(0, Long::sum); }
  • 6. Counting elements in a Stream long count = list.parallelStream().count(); When the examples get more complex, lambdas become much more interesting.
  • 7. Porting a legacy C# application For the last 8 months, Higher Frequency Trading ported 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?
  • 8. Summing BigDecimal getResults().stream() .reduce(BigDecimal.ZERO, (bd, t) -> bd.add(t.getRequirement()), BigDecimal::add);
  • 10. Sorting by multiple fields. setTrades(trades.stream() .sorted(comparing(t -> t.getInfo().getDate()) .thenComparing(Position::getCUSIP) .thenComparing(Position::getQuantity) .reversed()) .collect(toList()));
  • 11. Sorting by multiple fields, Quantity reversed setTrades(trades.stream() .sorted(comparing(t -> t.getInfo().getDate()) .thenComparing(Position::getCUSIP) .reversed() .thenComparing(Position::getQuantity) .reversed()) .collect(toList()));
  • 12. Group By Map<String, List<Position>> positionBySymbol = positions.values().stream() .filter(p -> p.getQuantity() != 0) .collect(groupingBy(Position::getSymbol));
  • 13. Streaming Maps pos.entrySet().stream() .filter(p -> p.getValue().getQuantity() != 0.0) .forEach(p -> pos2.put(p.getKey(), p.getValue()));
  • 14. Contains 2.0 if (list.stream() .anyMatch(p -> p.getType() == Type.Cash)) {
  • 15. Deep copy List<Position> newPositions = classPos.stream() .map(Position::clone) .collect(toList())
  • 16. To collect or not to collect (anti-pattern) getTrades().stream() .filter(t -> getDate().equals(t.getInfo().getDate())) .collect(toList()) .forEach(t -> trades.add(t.getInfo()));
  • 17. To collect or not to collect (solution) List<TradeInfo> trades = getTrades().stream() .filter(t -> getDate().equals( t.getInfo().getDate())) .map(Trade::getInfo) .collect(toList());
  • 18. Sort of sorted (anti-pattern) Map<Date, List<Trade>> groupTrades = trades.stream() .sorted(comparing(Trade::getDate)) .collect(groupingBy(Trade::getDate));
  • 19. Sorting (solution) Map<Date, List<Trade>> groupTrades = trades.stream() .collect(groupingBy( TradeDetail::getTradeDate, TreeMap::new, toList()));
  • 20. 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()); See slide 2 example for solution.
  • 21. Concurrent removal ? anti-pattern ? input.stream() .filter(t -> t.getParent() == p.getParent()) .forEach(input::remove);
  • 22. Optional Denial Position todayPos = newPos.stream() .filter(pos -> pos.getCUSIP() .equals(p.getCUSIP())) .findFirst().orElse(null); if (todayPos != null) {
  • 23. 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){
  • 24. Optional for equals public boolean equals(Object obj) { return Optional.ofNullable(obj) .filter(that -> that instanceof Test) .map(that -> (Test)that) .filter(that -> Objects.equals(this.s1, that.s1)) .filter(that -> Objects.equals(this.s2, that.s2)) .isPresent(); } Posted by Marko Topolnik
  • 25. Find the twenty most frequent words in a file To use parallel or not? 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());
  • 26. Lambdas and templates (before Java 8) long value; this.lock.lock(); try { value = doSomething(); } finally { this.lock.unlock(); }
  • 27. Lambdas and templates (with Java 8) public static <R> R with(Lock lock, Callable<R> work) { lock.lock(); try { return work.call(); } finally { lock.unlock(); } }
  • 28. Lambdas and templates (with Java 8) long value = with(lock, this::doSomething); Note: with inlining, the temporary “Long” object can be eliminated.
  • 29. Lambdas and performance public void readMarshallable(Wire wire) { wire.read(Fields.I).int32(x -> i = x) .read(Fields.J).int32(x -> j = x) .read(Fields.K).int32(x -> k = x) .read(Fields.L).int32(x -> l = x) .read(Fields.M).int32(x -> m = x) .read(Fields.N).int32(x -> n = x) .read(Fields.O).int32(x -> o = x) .read(Fields.P).int32(x -> p = x); }
  • 30. Lambdas and performance garbage in bytes per lambda
  • 31. Lambdas and performance -XX:BCEATraceLevel=3 Prints messages like Skipping method because: code size (271) exceeds MaxBCEAEstimateSize (150). So I raised the -XX:MaxBCEAEstimateSize=300
  • 32. Lambda type inference • Java 8 uses type inference much more than before. • Inference can appear to be as a cast. // error type is not known. Object o = () -> System.out::println; // type is inferred. Runnable o = () -> System.out::println; // type is inferred not cast at runtime. Object o = (Runnable & Serializable) () -> System.out::println;
  • 33. Lambda internals • Classes for Lambdas are generated at runtime. lambda.getClass() still works. • The contents of code in a lambda is added as a static method, except … • When a lambda expression refers to a method e.g. this::method or Class::new no additional method is created. • Provided your code is inlined, the lambda “object” can be eliminated. This also works for anonymous inner classes.
  • 34. End randomly (Don’t try this at home) IntStream.range(0, 128).parallel() .forEach(System::exit);