SlideShare a Scribd company logo
1 of 27
© Copyright Azul Systems 2016
© Copyright Azul Systems 2015
@speakjava
Streams in JDK 8:
The Good, The Bad & The Ugly
Simon Ritter
Deputy CTO, Azul Systems
1
© Copyright Azul Systems 2016
Goals Of This BoF
 Look at Streams code
 Discuss whether it’s good, bad or ugly
 Learn some things to do
 And some things not to do
 Idea came about because someone didn’t like my code
2
© Copyright Azul Systems 2016
Problem To Solve
 Code to extract key-value pairs from HTTP parameters
 Results:
– action, validate
– key, [10, 22, 10, 33]
3
action=validate&key=10&key=22&key=10&key=33
© Copyright Azul Systems 2016
Non-Stream Code
private void parseQuery(String query, Map parameters) {
if (query != null) {
String pairs[] = query.split("[&]");
for (String pair : pairs) {
String param[] = pair.split("[=]");
String key = null;
String value = null;
if (param.length > 0)
key = URLDecoder.decode(param[0], ENC);
if (param.length > 1)
value = URLDecoder.decode(param[1], ENC);
© Copyright Azul Systems 2016
Non-Stream Code
if (parameters.containsKey(key)) {
Object obj = parameters.get(key);
if (obj instanceof List) {
List values = (List)obj;
values.add(value);
} else if(obj instanceof String) {
List values = new ArrayList();
values.add((String)obj);
values.add(value);
parameters.put(key, values);
}
} else
parameters.put(key, value);
© Copyright Azul Systems 2016
My Stream Code (First Pass)
 Two problems
– Returns a null (ooh, bad!)
– Does not URLDecoder.decode() like original code
 decode() throws an exception
private Map<String, List<String>> parseQuery(String query) {
return (query == null) ? null : Arrays.stream(query.split("[&]"))
.collect(groupingBy(s -> (s.split("[=]"))[0],
mapping(s -> (s.split("[=]"))[1], toList())));
}
© Copyright Azul Systems 2016
My Stream Code (Updated)
AbstractMap.SimpleImmutableEntry<String, String>
splitKeyValue(String keyValue) {
String[] parts = keyValue.split(“[=]”);
try {
return new AbstractMap.SimpleImmutableEntry<>(
URLDecoder.decode(parts[0], ENC),
URLDecoder.decode(parts[1], ENC));
} catch (UnsupportedEncodingException uee) {
logger.warning(“Exception processing key-value pair”);
return null;
}
}
© Copyright Azul Systems 2016
My Stream Code (Updated)
private Map<String, List<String>> parseQuery(String query) {
return (query == null) ? new HashMap<String, List<String>>() :
Arrays.stream(query.split("[&]"))
.map(this::splitKeyValue)
.filter(e -> e != null)
.collect(groupingBy(Map.Entry::getKey,
mapping(Map.Entry::getValue, toList())));
}
© Copyright Azul Systems 2016
Stream Reuse (Good or Bad?)
IntStream stream = IntStream.of(1, 10);
stream.forEach(System.out::println);
/* Efficient use of resources? */
stream.forEach(System.out::println);
IllegalStateException: stream has already been operated upon or closed
Streams are single use
© Copyright Azul Systems 2016
Filter Confusion
Files.walk(Paths.get("."))
.filter(p -> !p.toFile().getName().startsWith("."))
.forEach(System.out::println);
Stream contains all
files and directories
Only checking the file name
(not parent directory)foo
bar
.home/baz
© Copyright Azul Systems 2016
Don’t Forget The Terminator
IntStream.range(1, 5)
.peek(System.out::println)
.peek(i -> {
if (i == 5)
throw new RuntimeException("bang!");
});
System.out.println(“Done!”);
Done!
© Copyright Azul Systems 2016
Streams Can Be Infinite
Even when you don’t want them to be
IntStream.iterate(0, i -> (i + 1) % 2)
.distinct()
.limit(10)
.forEach(System.out::println);
Infinite stream of 0, 1, 0, 1...
Only 0 and 1
10 elements will
never be found in
the stream
Prints
0
1
(But code never proceeds)
© Copyright Azul Systems 2016 13
Concatenate the first word of each string in a List
Simple Exercise
StringBuilder sb = new StringBuilder();
input.forEach(s -> sb.append(s.charAt(0)));
String result = sb.toString();
String result = input.stream()
.map(s -> s.substring(0, 1))
.reduce("", (a, b) -> a + b);
© Copyright Azul Systems 2016
Simple Exercise
14
StringBuilder sb = new StringBuilder();
Optional<String> optResult = input.stream()
.map(s -> s.substring(0, 1)
.reduce((a, b) -> sb.append(b).toString());
String result = optResult.orElse(“”);
FAIL!!
result = “bcdef”
© Copyright Azul Systems 2016 15
Simple Exercise
StringBuilder sb = new StringBuilder();
Optional<String> optResult = input.stream()
.map(s -> s.substring(0, 1)
.reduce((a, b) -> {
if (a.length() == 1)
sb.append(a);
return sb.append(b).toString();
});
String result = optResult.orElse(“”);
© Copyright Azul Systems 2016 16
Simple Exercise
String result = input.stream()
.map(s -> s.substring(0, 1))
.collect(Collector.of(
StringBuilder::new, // Supplier
StringBuilder::append, // Accumulator
StringBuilder::append, // Combiner
StringBuilder::toString, // Finisher
new Collector.Characteristics[0]));
© Copyright Azul Systems 2016 17
Simple Exercise
String result = input.stream()
.map(s -> s.substring(0, 1))
.collect(Collectors.joining());
© Copyright Azul Systems 2016
Which Is Better, And Why?
18
points.stream()
.filter(p -> p.isInView())
.map(p -> p.invert())
.forEach(p -> System.out.println(p));
points.stream()
.filter(GraphicPoint::isInView)
.map(GraphicPoint::invert)
.forEach(System.out::println);
© Copyright Azul Systems 2016
Parallel Streams Are Faster, Right?
 Not guaranteed
 A parallel stream will definitey do more work
– It just might finish quicker
 Parallel streams use the common fork-join pool
– Defaults to number of threads = number of CPUs
© Copyright Azul Systems 2016
Nesting Parallel Streams
List<Review> result = reviews.parallelStream()
.filter(review -> review.getImages()
.stream()
.parallel()
.anyMatch(image -> image.getIdImage() == 123))
.collect(Collectors.toList());
This will work, but will probably give worse
performance than using a serial stream
© Copyright Azul Systems 2016
Multi-Sort (The Bad)
patientRecords.stream()
.filter(this::isValidRecord)
.sorted(comparing(Patient::getName))
.sorted(comparing(Patient::getPhysician))
.sorted(comparing(Patient::getMedication))
.collect(toList());
© Copyright Azul Systems 2016
Multi-Sort (The Good)
patientRecords.stream()
.filter(this::isValidRecord)
.sorted(comparing(Patient::getMedication)
.thenComparing(comparing(Patient::getPhysician))
.thenComparing(comparing(Patient::getName)))
.collect(toList());
© Copyright Azul Systems 2016
Imperative Streams
LongAdder newMethodCount = new LongAdder();
map.get(class).stream()
.forEach(method -> {
output.println(val);
if (isNewMethod(class, method))
newMethodCount.increment();
});
© Copyright Azul Systems 2016
A Bit More Functional
int count = functionalParameterMethodMap.get(c).stream()
.mapToInt(m -> {
int newMethod = 0;
output.println(m);
if (isNewMethod(c, m))
newMethod = 1;
return newMethod
})
.sum();
There is still state
being modified in the
Lambda
© Copyright Azul Systems 2016
Almost Functional (But Not Quite)
int count = functionalParameterMethodMap.get(nameOfClass)
.stream()
.peek(method -> output.println(method))
.mapToInt(m -> isNewMethod(nameOfClass, m) ? 1 : 0)
.sum();
Strictly speaking printing is
a side effect, which is not
purely functional
© Copyright Azul Systems 2016
Conclusions
 Streams are powerful
– With great power comes great responsibility
 Try not to think imperatively
– forEach is good, but not for each (and every) situation
 Part of streams power is clarity of code
– That doesn’t mean as few lines as possible!
 Parallel does not guarantee faster
26
© Copyright Azul Systems 2016
© Copyright Azul Systems 2015
@speakjava
Streams in JDK 8:
The Good, The Bad & The Ugly
Simon Ritter
Deputy CTO, Azul Systems
27

More Related Content

What's hot

An Introduction to Higher Order Functions in Spark SQL with Herman van Hovell
An Introduction to Higher Order Functions in Spark SQL with Herman van HovellAn Introduction to Higher Order Functions in Spark SQL with Herman van Hovell
An Introduction to Higher Order Functions in Spark SQL with Herman van HovellDatabricks
 
Ge aviation spark application experience porting analytics into py spark ml p...
Ge aviation spark application experience porting analytics into py spark ml p...Ge aviation spark application experience porting analytics into py spark ml p...
Ge aviation spark application experience porting analytics into py spark ml p...Databricks
 
Harnessing the Power of Java 8 Streams
Harnessing the Power of Java 8 Streams Harnessing the Power of Java 8 Streams
Harnessing the Power of Java 8 Streams IndicThreads
 
Kotlin Receiver Types 介紹
Kotlin Receiver Types 介紹Kotlin Receiver Types 介紹
Kotlin Receiver Types 介紹Kros Huang
 
Shooting the Rapids: Getting the Best from Java 8 Streams
Shooting the Rapids: Getting the Best from Java 8 StreamsShooting the Rapids: Getting the Best from Java 8 Streams
Shooting the Rapids: Getting the Best from Java 8 StreamsMaurice Naftalin
 
Spark Schema For Free with David Szakallas
 Spark Schema For Free with David Szakallas Spark Schema For Free with David Szakallas
Spark Schema For Free with David SzakallasDatabricks
 
Good and Wicked Fairies, and the Tragedy of the Commons: Understanding the Pe...
Good and Wicked Fairies, and the Tragedy of the Commons: Understanding the Pe...Good and Wicked Fairies, and the Tragedy of the Commons: Understanding the Pe...
Good and Wicked Fairies, and the Tragedy of the Commons: Understanding the Pe...Maurice Naftalin
 
Parallel-Ready Java Code: Managing Mutation in an Imperative Language
Parallel-Ready Java Code: Managing Mutation in an Imperative LanguageParallel-Ready Java Code: Managing Mutation in an Imperative Language
Parallel-Ready Java Code: Managing Mutation in an Imperative LanguageMaurice Naftalin
 
Brief introduction on Hadoop,Dremel, Pig, FlumeJava and Cassandra
Brief introduction on Hadoop,Dremel, Pig, FlumeJava and CassandraBrief introduction on Hadoop,Dremel, Pig, FlumeJava and Cassandra
Brief introduction on Hadoop,Dremel, Pig, FlumeJava and CassandraSomnath Mazumdar
 
Apache Flink Training: DataStream API Part 2 Advanced
Apache Flink Training: DataStream API Part 2 Advanced Apache Flink Training: DataStream API Part 2 Advanced
Apache Flink Training: DataStream API Part 2 Advanced Flink Forward
 
Lambdas and Streams in Java SE 8: Making Bulk Operations simple - Simon Ritter
Lambdas and Streams in Java SE 8: Making Bulk Operations simple - Simon RitterLambdas and Streams in Java SE 8: Making Bulk Operations simple - Simon Ritter
Lambdas and Streams in Java SE 8: Making Bulk Operations simple - Simon RitterJAXLondon2014
 
Vasia Kalavri – Training: Gelly School
Vasia Kalavri – Training: Gelly School Vasia Kalavri – Training: Gelly School
Vasia Kalavri – Training: Gelly School Flink Forward
 
How to Think in RxJava Before Reacting
How to Think in RxJava Before ReactingHow to Think in RxJava Before Reacting
How to Think in RxJava Before ReactingIndicThreads
 
Flink Batch Processing and Iterations
Flink Batch Processing and IterationsFlink Batch Processing and Iterations
Flink Batch Processing and IterationsSameer Wadkar
 

What's hot (20)

An Introduction to Higher Order Functions in Spark SQL with Herman van Hovell
An Introduction to Higher Order Functions in Spark SQL with Herman van HovellAn Introduction to Higher Order Functions in Spark SQL with Herman van Hovell
An Introduction to Higher Order Functions in Spark SQL with Herman van Hovell
 
Ge aviation spark application experience porting analytics into py spark ml p...
Ge aviation spark application experience porting analytics into py spark ml p...Ge aviation spark application experience porting analytics into py spark ml p...
Ge aviation spark application experience porting analytics into py spark ml p...
 
Shooting the Rapids
Shooting the RapidsShooting the Rapids
Shooting the Rapids
 
Harnessing the Power of Java 8 Streams
Harnessing the Power of Java 8 Streams Harnessing the Power of Java 8 Streams
Harnessing the Power of Java 8 Streams
 
Kotlin Receiver Types 介紹
Kotlin Receiver Types 介紹Kotlin Receiver Types 介紹
Kotlin Receiver Types 介紹
 
Shooting the Rapids: Getting the Best from Java 8 Streams
Shooting the Rapids: Getting the Best from Java 8 StreamsShooting the Rapids: Getting the Best from Java 8 Streams
Shooting the Rapids: Getting the Best from Java 8 Streams
 
Array list
Array listArray list
Array list
 
Spark Schema For Free with David Szakallas
 Spark Schema For Free with David Szakallas Spark Schema For Free with David Szakallas
Spark Schema For Free with David Szakallas
 
Let's Get to the Rapids
Let's Get to the RapidsLet's Get to the Rapids
Let's Get to the Rapids
 
Good and Wicked Fairies, and the Tragedy of the Commons: Understanding the Pe...
Good and Wicked Fairies, and the Tragedy of the Commons: Understanding the Pe...Good and Wicked Fairies, and the Tragedy of the Commons: Understanding the Pe...
Good and Wicked Fairies, and the Tragedy of the Commons: Understanding the Pe...
 
Parallel-Ready Java Code: Managing Mutation in an Imperative Language
Parallel-Ready Java Code: Managing Mutation in an Imperative LanguageParallel-Ready Java Code: Managing Mutation in an Imperative Language
Parallel-Ready Java Code: Managing Mutation in an Imperative Language
 
Brief introduction on Hadoop,Dremel, Pig, FlumeJava and Cassandra
Brief introduction on Hadoop,Dremel, Pig, FlumeJava and CassandraBrief introduction on Hadoop,Dremel, Pig, FlumeJava and Cassandra
Brief introduction on Hadoop,Dremel, Pig, FlumeJava and Cassandra
 
Apache Flink Training: DataStream API Part 2 Advanced
Apache Flink Training: DataStream API Part 2 Advanced Apache Flink Training: DataStream API Part 2 Advanced
Apache Flink Training: DataStream API Part 2 Advanced
 
Lambdas and Streams in Java SE 8: Making Bulk Operations simple - Simon Ritter
Lambdas and Streams in Java SE 8: Making Bulk Operations simple - Simon RitterLambdas and Streams in Java SE 8: Making Bulk Operations simple - Simon Ritter
Lambdas and Streams in Java SE 8: Making Bulk Operations simple - Simon Ritter
 
R and C++
R and C++R and C++
R and C++
 
R and cpp
R and cppR and cpp
R and cpp
 
Vasia Kalavri – Training: Gelly School
Vasia Kalavri – Training: Gelly School Vasia Kalavri – Training: Gelly School
Vasia Kalavri – Training: Gelly School
 
How to Think in RxJava Before Reacting
How to Think in RxJava Before ReactingHow to Think in RxJava Before Reacting
How to Think in RxJava Before Reacting
 
Spark workshop
Spark workshopSpark workshop
Spark workshop
 
Flink Batch Processing and Iterations
Flink Batch Processing and IterationsFlink Batch Processing and Iterations
Flink Batch Processing and Iterations
 

Similar to Streams: The Good, The Bad And The Ugly

RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]Igor Lozynskyi
 
JS Fest 2019. Anjana Vakil. Serverless Bebop
JS Fest 2019. Anjana Vakil. Serverless BebopJS Fest 2019. Anjana Vakil. Serverless Bebop
JS Fest 2019. Anjana Vakil. Serverless BebopJSFestUA
 
Functional Thinking for Java Developers (presented in Javafest Bengaluru)
Functional Thinking for Java Developers (presented in Javafest Bengaluru)Functional Thinking for Java Developers (presented in Javafest Bengaluru)
Functional Thinking for Java Developers (presented in Javafest Bengaluru)KonfHubTechConferenc
 
Ingesting streaming data for analysis in apache ignite (stream sets theme)
Ingesting streaming data for analysis in apache ignite (stream sets theme)Ingesting streaming data for analysis in apache ignite (stream sets theme)
Ingesting streaming data for analysis in apache ignite (stream sets theme)Tom Diederich
 
Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)Ganesh Samarthyam
 
Introduction to Apache Flink
Introduction to Apache FlinkIntroduction to Apache Flink
Introduction to Apache Flinkmxmxm
 
[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기NAVER D2
 
Presto anatomy
Presto anatomyPresto anatomy
Presto anatomyDongmin Yu
 
Java 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually useJava 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually useSharon Rozinsky
 
Web program-peformance-optimization
Web program-peformance-optimizationWeb program-peformance-optimization
Web program-peformance-optimizationxiaojueqq12345
 
Model-based GUI testing using UPPAAL
Model-based GUI testing using UPPAALModel-based GUI testing using UPPAAL
Model-based GUI testing using UPPAALUlrik Hørlyk Hjort
 
Artem Storozhuk "Building SQL firewall: insights from developers"
Artem Storozhuk "Building SQL firewall: insights from developers"Artem Storozhuk "Building SQL firewall: insights from developers"
Artem Storozhuk "Building SQL firewall: insights from developers"Fwdays
 
Gdg almaty. Функциональное программирование в Java 8
Gdg almaty. Функциональное программирование в Java 8Gdg almaty. Функциональное программирование в Java 8
Gdg almaty. Функциональное программирование в Java 8Madina Kamzina
 
java 8 Hands on Workshop
java 8 Hands on Workshopjava 8 Hands on Workshop
java 8 Hands on WorkshopJeanne Boyarsky
 

Similar to Streams: The Good, The Bad And The Ugly (20)

RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]
 
Java Language fundamental
Java Language fundamentalJava Language fundamental
Java Language fundamental
 
JS Fest 2019. Anjana Vakil. Serverless Bebop
JS Fest 2019. Anjana Vakil. Serverless BebopJS Fest 2019. Anjana Vakil. Serverless Bebop
JS Fest 2019. Anjana Vakil. Serverless Bebop
 
What is new in Java 8
What is new in Java 8What is new in Java 8
What is new in Java 8
 
Functional Thinking for Java Developers (presented in Javafest Bengaluru)
Functional Thinking for Java Developers (presented in Javafest Bengaluru)Functional Thinking for Java Developers (presented in Javafest Bengaluru)
Functional Thinking for Java Developers (presented in Javafest Bengaluru)
 
Ingesting streaming data for analysis in apache ignite (stream sets theme)
Ingesting streaming data for analysis in apache ignite (stream sets theme)Ingesting streaming data for analysis in apache ignite (stream sets theme)
Ingesting streaming data for analysis in apache ignite (stream sets theme)
 
Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)
 
Introduction to Apache Flink
Introduction to Apache FlinkIntroduction to Apache Flink
Introduction to Apache Flink
 
[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기
 
Presto anatomy
Presto anatomyPresto anatomy
Presto anatomy
 
Lambda Functions in Java 8
Lambda Functions in Java 8Lambda Functions in Java 8
Lambda Functions in Java 8
 
Java 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually useJava 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually use
 
Lambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter LawreyLambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter Lawrey
 
Web program-peformance-optimization
Web program-peformance-optimizationWeb program-peformance-optimization
Web program-peformance-optimization
 
Model-based GUI testing using UPPAAL
Model-based GUI testing using UPPAALModel-based GUI testing using UPPAAL
Model-based GUI testing using UPPAAL
 
Artem Storozhuk "Building SQL firewall: insights from developers"
Artem Storozhuk "Building SQL firewall: insights from developers"Artem Storozhuk "Building SQL firewall: insights from developers"
Artem Storozhuk "Building SQL firewall: insights from developers"
 
Modern Java Development
Modern Java DevelopmentModern Java Development
Modern Java Development
 
Gdg almaty. Функциональное программирование в Java 8
Gdg almaty. Функциональное программирование в Java 8Gdg almaty. Функциональное программирование в Java 8
Gdg almaty. Функциональное программирование в Java 8
 
Sailing with Java 8 Streams
Sailing with Java 8 StreamsSailing with Java 8 Streams
Sailing with Java 8 Streams
 
java 8 Hands on Workshop
java 8 Hands on Workshopjava 8 Hands on Workshop
java 8 Hands on Workshop
 

More from Simon Ritter

Cloud Native Compiler
Cloud Native CompilerCloud Native Compiler
Cloud Native CompilerSimon Ritter
 
The Art of Java Type Patterns
The Art of Java Type PatternsThe Art of Java Type Patterns
The Art of Java Type PatternsSimon Ritter
 
Modern Java Workshop
Modern Java WorkshopModern Java Workshop
Modern Java WorkshopSimon Ritter
 
Java performance monitoring
Java performance monitoringJava performance monitoring
Java performance monitoringSimon Ritter
 
Modern Java Workshop
Modern Java WorkshopModern Java Workshop
Modern Java WorkshopSimon Ritter
 
Getting the Most From Modern Java
Getting the Most From Modern JavaGetting the Most From Modern Java
Getting the Most From Modern JavaSimon Ritter
 
Building a Better JVM
Building a Better JVMBuilding a Better JVM
Building a Better JVMSimon Ritter
 
JDK 14 Lots of New Features
JDK 14 Lots of New FeaturesJDK 14 Lots of New Features
JDK 14 Lots of New FeaturesSimon Ritter
 
How to Choose a JDK
How to Choose a JDKHow to Choose a JDK
How to Choose a JDKSimon Ritter
 
The Latest in Enterprise JavaBeans Technology
The Latest in Enterprise JavaBeans TechnologyThe Latest in Enterprise JavaBeans Technology
The Latest in Enterprise JavaBeans TechnologySimon Ritter
 
Developing Enterprise Applications Using Java Technology
Developing Enterprise Applications Using Java TechnologyDeveloping Enterprise Applications Using Java Technology
Developing Enterprise Applications Using Java TechnologySimon Ritter
 
Is Java Still Free?
Is Java Still Free?Is Java Still Free?
Is Java Still Free?Simon Ritter
 
Moving Towards JDK 12
Moving Towards JDK 12Moving Towards JDK 12
Moving Towards JDK 12Simon Ritter
 
JDK 9, 10, 11 and Beyond
JDK 9, 10, 11 and BeyondJDK 9, 10, 11 and Beyond
JDK 9, 10, 11 and BeyondSimon Ritter
 
Java Is Still Free
Java Is Still FreeJava Is Still Free
Java Is Still FreeSimon Ritter
 
JDK 9, 10, 11 and Beyond
JDK 9, 10, 11 and BeyondJDK 9, 10, 11 and Beyond
JDK 9, 10, 11 and BeyondSimon Ritter
 
JDK 9 and JDK 10 Deep Dive
JDK 9 and JDK 10 Deep DiveJDK 9 and JDK 10 Deep Dive
JDK 9 and JDK 10 Deep DiveSimon Ritter
 

More from Simon Ritter (20)

Cloud Native Compiler
Cloud Native CompilerCloud Native Compiler
Cloud Native Compiler
 
Java On CRaC
Java On CRaCJava On CRaC
Java On CRaC
 
The Art of Java Type Patterns
The Art of Java Type PatternsThe Art of Java Type Patterns
The Art of Java Type Patterns
 
Modern Java Workshop
Modern Java WorkshopModern Java Workshop
Modern Java Workshop
 
Java performance monitoring
Java performance monitoringJava performance monitoring
Java performance monitoring
 
Modern Java Workshop
Modern Java WorkshopModern Java Workshop
Modern Java Workshop
 
Getting the Most From Modern Java
Getting the Most From Modern JavaGetting the Most From Modern Java
Getting the Most From Modern Java
 
Building a Better JVM
Building a Better JVMBuilding a Better JVM
Building a Better JVM
 
JDK 14 Lots of New Features
JDK 14 Lots of New FeaturesJDK 14 Lots of New Features
JDK 14 Lots of New Features
 
Java after 8
Java after 8Java after 8
Java after 8
 
How to Choose a JDK
How to Choose a JDKHow to Choose a JDK
How to Choose a JDK
 
Java Programming
Java ProgrammingJava Programming
Java Programming
 
The Latest in Enterprise JavaBeans Technology
The Latest in Enterprise JavaBeans TechnologyThe Latest in Enterprise JavaBeans Technology
The Latest in Enterprise JavaBeans Technology
 
Developing Enterprise Applications Using Java Technology
Developing Enterprise Applications Using Java TechnologyDeveloping Enterprise Applications Using Java Technology
Developing Enterprise Applications Using Java Technology
 
Is Java Still Free?
Is Java Still Free?Is Java Still Free?
Is Java Still Free?
 
Moving Towards JDK 12
Moving Towards JDK 12Moving Towards JDK 12
Moving Towards JDK 12
 
JDK 9, 10, 11 and Beyond
JDK 9, 10, 11 and BeyondJDK 9, 10, 11 and Beyond
JDK 9, 10, 11 and Beyond
 
Java Is Still Free
Java Is Still FreeJava Is Still Free
Java Is Still Free
 
JDK 9, 10, 11 and Beyond
JDK 9, 10, 11 and BeyondJDK 9, 10, 11 and Beyond
JDK 9, 10, 11 and Beyond
 
JDK 9 and JDK 10 Deep Dive
JDK 9 and JDK 10 Deep DiveJDK 9 and JDK 10 Deep Dive
JDK 9 and JDK 10 Deep Dive
 

Recently uploaded

cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptrcbcrtm
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Software Coding for software engineering
Software Coding for software engineeringSoftware Coding for software engineering
Software Coding for software engineeringssuserb3a23b
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfkalichargn70th171
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 

Recently uploaded (20)

cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.ppt
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Software Coding for software engineering
Software Coding for software engineeringSoftware Coding for software engineering
Software Coding for software engineering
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 

Streams: The Good, The Bad And The Ugly

  • 1. © Copyright Azul Systems 2016 © Copyright Azul Systems 2015 @speakjava Streams in JDK 8: The Good, The Bad & The Ugly Simon Ritter Deputy CTO, Azul Systems 1
  • 2. © Copyright Azul Systems 2016 Goals Of This BoF  Look at Streams code  Discuss whether it’s good, bad or ugly  Learn some things to do  And some things not to do  Idea came about because someone didn’t like my code 2
  • 3. © Copyright Azul Systems 2016 Problem To Solve  Code to extract key-value pairs from HTTP parameters  Results: – action, validate – key, [10, 22, 10, 33] 3 action=validate&key=10&key=22&key=10&key=33
  • 4. © Copyright Azul Systems 2016 Non-Stream Code private void parseQuery(String query, Map parameters) { if (query != null) { String pairs[] = query.split("[&]"); for (String pair : pairs) { String param[] = pair.split("[=]"); String key = null; String value = null; if (param.length > 0) key = URLDecoder.decode(param[0], ENC); if (param.length > 1) value = URLDecoder.decode(param[1], ENC);
  • 5. © Copyright Azul Systems 2016 Non-Stream Code if (parameters.containsKey(key)) { Object obj = parameters.get(key); if (obj instanceof List) { List values = (List)obj; values.add(value); } else if(obj instanceof String) { List values = new ArrayList(); values.add((String)obj); values.add(value); parameters.put(key, values); } } else parameters.put(key, value);
  • 6. © Copyright Azul Systems 2016 My Stream Code (First Pass)  Two problems – Returns a null (ooh, bad!) – Does not URLDecoder.decode() like original code  decode() throws an exception private Map<String, List<String>> parseQuery(String query) { return (query == null) ? null : Arrays.stream(query.split("[&]")) .collect(groupingBy(s -> (s.split("[=]"))[0], mapping(s -> (s.split("[=]"))[1], toList()))); }
  • 7. © Copyright Azul Systems 2016 My Stream Code (Updated) AbstractMap.SimpleImmutableEntry<String, String> splitKeyValue(String keyValue) { String[] parts = keyValue.split(“[=]”); try { return new AbstractMap.SimpleImmutableEntry<>( URLDecoder.decode(parts[0], ENC), URLDecoder.decode(parts[1], ENC)); } catch (UnsupportedEncodingException uee) { logger.warning(“Exception processing key-value pair”); return null; } }
  • 8. © Copyright Azul Systems 2016 My Stream Code (Updated) private Map<String, List<String>> parseQuery(String query) { return (query == null) ? new HashMap<String, List<String>>() : Arrays.stream(query.split("[&]")) .map(this::splitKeyValue) .filter(e -> e != null) .collect(groupingBy(Map.Entry::getKey, mapping(Map.Entry::getValue, toList()))); }
  • 9. © Copyright Azul Systems 2016 Stream Reuse (Good or Bad?) IntStream stream = IntStream.of(1, 10); stream.forEach(System.out::println); /* Efficient use of resources? */ stream.forEach(System.out::println); IllegalStateException: stream has already been operated upon or closed Streams are single use
  • 10. © Copyright Azul Systems 2016 Filter Confusion Files.walk(Paths.get(".")) .filter(p -> !p.toFile().getName().startsWith(".")) .forEach(System.out::println); Stream contains all files and directories Only checking the file name (not parent directory)foo bar .home/baz
  • 11. © Copyright Azul Systems 2016 Don’t Forget The Terminator IntStream.range(1, 5) .peek(System.out::println) .peek(i -> { if (i == 5) throw new RuntimeException("bang!"); }); System.out.println(“Done!”); Done!
  • 12. © Copyright Azul Systems 2016 Streams Can Be Infinite Even when you don’t want them to be IntStream.iterate(0, i -> (i + 1) % 2) .distinct() .limit(10) .forEach(System.out::println); Infinite stream of 0, 1, 0, 1... Only 0 and 1 10 elements will never be found in the stream Prints 0 1 (But code never proceeds)
  • 13. © Copyright Azul Systems 2016 13 Concatenate the first word of each string in a List Simple Exercise StringBuilder sb = new StringBuilder(); input.forEach(s -> sb.append(s.charAt(0))); String result = sb.toString(); String result = input.stream() .map(s -> s.substring(0, 1)) .reduce("", (a, b) -> a + b);
  • 14. © Copyright Azul Systems 2016 Simple Exercise 14 StringBuilder sb = new StringBuilder(); Optional<String> optResult = input.stream() .map(s -> s.substring(0, 1) .reduce((a, b) -> sb.append(b).toString()); String result = optResult.orElse(“”); FAIL!! result = “bcdef”
  • 15. © Copyright Azul Systems 2016 15 Simple Exercise StringBuilder sb = new StringBuilder(); Optional<String> optResult = input.stream() .map(s -> s.substring(0, 1) .reduce((a, b) -> { if (a.length() == 1) sb.append(a); return sb.append(b).toString(); }); String result = optResult.orElse(“”);
  • 16. © Copyright Azul Systems 2016 16 Simple Exercise String result = input.stream() .map(s -> s.substring(0, 1)) .collect(Collector.of( StringBuilder::new, // Supplier StringBuilder::append, // Accumulator StringBuilder::append, // Combiner StringBuilder::toString, // Finisher new Collector.Characteristics[0]));
  • 17. © Copyright Azul Systems 2016 17 Simple Exercise String result = input.stream() .map(s -> s.substring(0, 1)) .collect(Collectors.joining());
  • 18. © Copyright Azul Systems 2016 Which Is Better, And Why? 18 points.stream() .filter(p -> p.isInView()) .map(p -> p.invert()) .forEach(p -> System.out.println(p)); points.stream() .filter(GraphicPoint::isInView) .map(GraphicPoint::invert) .forEach(System.out::println);
  • 19. © Copyright Azul Systems 2016 Parallel Streams Are Faster, Right?  Not guaranteed  A parallel stream will definitey do more work – It just might finish quicker  Parallel streams use the common fork-join pool – Defaults to number of threads = number of CPUs
  • 20. © Copyright Azul Systems 2016 Nesting Parallel Streams List<Review> result = reviews.parallelStream() .filter(review -> review.getImages() .stream() .parallel() .anyMatch(image -> image.getIdImage() == 123)) .collect(Collectors.toList()); This will work, but will probably give worse performance than using a serial stream
  • 21. © Copyright Azul Systems 2016 Multi-Sort (The Bad) patientRecords.stream() .filter(this::isValidRecord) .sorted(comparing(Patient::getName)) .sorted(comparing(Patient::getPhysician)) .sorted(comparing(Patient::getMedication)) .collect(toList());
  • 22. © Copyright Azul Systems 2016 Multi-Sort (The Good) patientRecords.stream() .filter(this::isValidRecord) .sorted(comparing(Patient::getMedication) .thenComparing(comparing(Patient::getPhysician)) .thenComparing(comparing(Patient::getName))) .collect(toList());
  • 23. © Copyright Azul Systems 2016 Imperative Streams LongAdder newMethodCount = new LongAdder(); map.get(class).stream() .forEach(method -> { output.println(val); if (isNewMethod(class, method)) newMethodCount.increment(); });
  • 24. © Copyright Azul Systems 2016 A Bit More Functional int count = functionalParameterMethodMap.get(c).stream() .mapToInt(m -> { int newMethod = 0; output.println(m); if (isNewMethod(c, m)) newMethod = 1; return newMethod }) .sum(); There is still state being modified in the Lambda
  • 25. © Copyright Azul Systems 2016 Almost Functional (But Not Quite) int count = functionalParameterMethodMap.get(nameOfClass) .stream() .peek(method -> output.println(method)) .mapToInt(m -> isNewMethod(nameOfClass, m) ? 1 : 0) .sum(); Strictly speaking printing is a side effect, which is not purely functional
  • 26. © Copyright Azul Systems 2016 Conclusions  Streams are powerful – With great power comes great responsibility  Try not to think imperatively – forEach is good, but not for each (and every) situation  Part of streams power is clarity of code – That doesn’t mean as few lines as possible!  Parallel does not guarantee faster 26
  • 27. © Copyright Azul Systems 2016 © Copyright Azul Systems 2015 @speakjava Streams in JDK 8: The Good, The Bad & The Ugly Simon Ritter Deputy CTO, Azul Systems 27