SlideShare uma empresa Scribd logo
1 de 55
© Copyright Azul Systems 2016
© Copyright Azul Systems 2015
@speakjava
Lessons Learnt With
Lambdas and Streams
in JDK 8
Simon Ritter
Deputy CTO, Azul Systems
1
© Copyright Azul Systems 2016
A clever man learns from his
mistakes...
...a wise man learns from
other people’s
© Copyright Azul Systems 2016
Agenda
 Lambdas and Streams Primer
 Delaying Execution
 Avoiding Loops In Streams
 The Art Of Reduction
 Parallel streams: myths and realities
 Lambdas and Streams and JDK 9
 Conclusions
3
© Copyright Azul Systems 2016
Lambdas And Streams Primer
© Copyright Azul Systems 2016
Lambda Expressions In JDK 8
 Old style, anonymous inner classes
 New style, using a Lambda expression
 Can be used wherever the type is a functional interface
5
Simplified Parameterised Behaviour
new Thread(new Runnable {
public void run() {
doSomeStuff();
}
}).start();
new Thread(() -> doSomeStuff()).start();
© Copyright Azul Systems 2016
Functional Interface Definition
 Is an interface
 Must have only one abstract method
– In JDK 7 this would mean only one method (like
ActionListener)
 JDK 8 introduced default methods
– Adding multiple inheritance of types to Java
– These are, by definition, not abstract
 JDK 8 also now allows interfaces to have static methods
 @FunctionalInterface to have the compiler check
6
© Copyright Azul Systems 2016
Type Inference
 Compiler can often infer parameter types in a lambda
expression
– Inferrence based on target functional interface’s method signature
 Fully statically typed (no dynamic typing sneaking in)
– More typing with less typing
static T void sort(List<T> l, Comparator<? super T> c);
List<String> list = getList();
Collections.sort(list, (String x, String y) -> x.length() > y.length());
Collections.sort(list, (x, y) -> x.length() - y.length());
© Copyright Azul Systems 2016
Stream Overview
 A stream pipeline consists of three types of things
– A source
– Zero or more intermediate operations
– A terminal operation
 Producing a result or a side-effect
int total = transactions.stream()
.filter(t -> t.getBuyer().getCity().equals(“London”))
.mapToInt(Transaction::getPrice)
.sum();
Source
Intermediate operation
Terminal operation
© Copyright Azul Systems 2016
Stream Terminal Operations
 The pipeline is only evaluated when the terminal operation
is called
– All operations can execute sequentially or in parallel
– Intermediate operations can be merged
 Avoiding multiple redundant passes on data
 Short-circuit operations (e.g. findFirst)
 Lazy evaluation
– Stream characteristics help identify optimisations
 DISTINT stream passed to distinct() is a no-op
© Copyright Azul Systems 2016
Optional Class
 Terminal operations like min(), max(), etc do not return a
direct result
– Suppose the input Stream is empty?
 Optional<T>
– Container for an object reference (null, or real object)
– Think of it like a Stream of 0 or 1 elements
– use get(), ifPresent() and orElse() to access the
stored reference
– Can use in more complex ways: filter(), map(), etc
© Copyright Azul Systems 2016
Lambda Expressions And
Delayed Execution
© Copyright Azul Systems 2016
Performance Impact For Logging
 Heisenberg’s uncertainty principle
 Setting log level to INFO still has a performance impact
 Since Logger determines whether to log the message the
parameter must be evaluated even when not used
12
logger.finest(getSomeStatusData());
Always executed
© Copyright Azul Systems 2016
Supplier<T>
 Represents a supplier of results
 All relevant logging methods now have a version that takes
a Supplier
 Pass a description of how to create the log message
– Not the message
 If the Logger doesn’t need the value it doesn’t invoke the
Lambda
 Can be used for other conditional activities
13
logger.finest(getSomeStatusData());logger.finest(() -> getSomeStatusData());
© Copyright Azul Systems 2016
Avoiding Loops In Streams
© Copyright Azul Systems 2016
Functional v. Imperative
 For functional programming you should not modify state
 Java supports closures over values, not closures over
variables
 But state is really useful…
15
© Copyright Azul Systems 2016
Counting Methods That Return Streams
16
Still Thinking Imperatively
Set<String> sourceKeySet =
streamReturningMethodMap.keySet();
LongAdder sourceCount = new LongAdder();
sourceKeySet.stream()
.forEach(c -> sourceCount
.add(streamReturningMethodMap.get(c).size()));
© Copyright Azul Systems 2016
Counting Methods That Return Streams
17
Functional Way
sourceKeySet.stream()
.mapToInt(c -> streamReturningMethodMap.get(c).size())
.sum();
© Copyright Azul Systems 2016
Printing And Counting
18
Still Thinking Imperatively
LongAdder newMethodCount = new LongAdder();
functionalParameterMethodMap.get(c).stream()
.forEach(m -> {
output.println(m);
if (isNewMethod(c, m))
newMethodCount.increment();
});
© Copyright Azul Systems 2016
Printing And Counting
19
More Functional, But Not Pure 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
Printing And Counting
20
Even More Functional, But Still Not Pure Functional
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
The Art Of Reduction
(Or The Need to Think
Differently)
© Copyright Azul Systems 2016
A Simple Problem
 Find the length of the longest line in a file
 Hint: BufferedReader has a new method, lines(), that
returns a Stream
22
BufferedReader reader = ...
int longest = reader.lines()
.mapToInt(String::length)
.max()
.getAsInt();
© Copyright Azul Systems 2016
Another Simple Problem
 Find the length of the longest line in a file
23
© Copyright Azul Systems 2016
Another Simple Problem
 Find the length of the longest line in a file
24
© Copyright Azul Systems 2016
Naïve Stream Solution
 That works, so job done, right?
 Not really. Big files will take a long time and a lot of
resources
 Must be a better approach
25
String longest = reader.lines().
sort((x, y) -> y.length() - x.length()).
findFirst().
get();
© Copyright Azul Systems 2016
External Iteration Solution
 Simple, but inherently serial
 Not thread safe due to mutable state
26
String longest = "";
while ((String s = reader.readLine()) != null)
if (s.length() > longest.length())
longest = s;
© Copyright Azul Systems 2016
Recursive Approach
27
String findLongestString(String longest, BufferedReader reader) {
String next = reader.readLine();
if (next == null)
return longest;
if (next.length() > longest.length())
longest = next;
return findLongestString(longest, reader);
}
© Copyright Azul Systems 2016
Recursion: Solving The Problem
 No explicit loop, no mutable state, we’re all good now, right?
 Unfortunately not:
– larger data sets will generate an OOM exception
– Too many stack frames
28
String longest = findLongestString("", reader);
© Copyright Azul Systems 2016
A Better Stream Solution
 Stream API uses the well known filter-map-reduce pattern
 For this problem we do not need to filter or map, just
reduce
Optional<T> reduce(BinaryOperator<T> accumulator)
 BinaryOperator is a subclass of BiFunction
– R apply(T t, U u)
 For BinaryOperator all types are the same
– T apply(T x, T y)
29
© Copyright Azul Systems 2016
A Better Stream Solution
 The key is to find the right accumulator
– The accumulator takes a partial result and the next
element, and returns a new partial result
– In essence it does the same as our recursive solution
– But without all the stack frames
30
© Copyright Azul Systems 2016
A Better Stream Solution
 Use the recursive approach as an accululator for a
reduction
31
String longestLine = reader.lines()
.reduce((x, y) -> {
if (x.length() > y.length())
return x;
return y;
})
.get();
© Copyright Azul Systems 2016
A Better Stream Solution
 Use the recursive approach as an accululator for a
reduction
32
String longestLine = reader.lines()
.reduce((x, y) -> {
if (x.length() > y.length())
return x;
return y;
})
.get();
x in effect maintains state
for us, by providing the
partial result, which is the
longest string found so far
© Copyright Azul Systems 2016
The Simplest Stream Solution
 Use a specialised form of max()
 One that takes a Comparator as a parameter
 comparingInt() is a static method on Comparator
Comparator<T> comparingInt(
ToIntFunction<? extends T> keyExtractor)
33
reader.lines()
.max(comparingInt(String::length))
.get();
© Copyright Azul Systems 2016
Parallel Streams:
Myths And Realities
© Copyright Azul Systems 2016 35
© Copyright Azul Systems 2016
Serial And Parallel Streams
 Syntactically very simple to change from serial to parallel
36
int sum = list.stream()
.filter(w -> w.getColour() == RED)
.mapToInt(w -> w.getWeight())
.sum();
int sum = list.parallelStream()
.filter(w -> w.getColour() == RED)
.mapToInt(w -> w.getWeight())
.sum();
© Copyright Azul Systems 2016
Serial And Parallel Streams
 Syntactically very simple to change from serial to parallel
 Use serial() or parallel() to change mid-stream
37
int sum = list.parallelStream()
.filter(w -> w.getColour() == RED)
.serial()
.mapToInt(w -> w.getWeight())
.parallel()
.sum();
© Copyright Azul Systems 2016
Serial And Parallel Streams
 Syntactically very simple to change from serial to parallel
 Use serial() or parallel() to change mid-stream
 Whole stream is processed serially or in parallel
– Last call wins
 Operations should be stateless and independent
38
int sum = list.parallelStream()
.filter(w -> w.getColour() == RED)
.serial()
.mapToInt(w -> w.getWeight())
.parallel()
.sum();
© Copyright Azul Systems 2016
Common ForkJoinPool
 Created when JVM starts up
 Default number of threads is equal to CPUs reported by OS
– Runtime.getRuntime().availableProcessors()
 Can be changed manually
39
-Djava.util.concurrent.ForkJoinPool.common.parallelism=n
© Copyright Azul Systems 2016
Common ForkJoinPool
40
Set<String> workers = new ConcurrentSet<String>();
int sum = list.parallelStream()
.peek(n -> workers.add(Thread.currentThread().getName()))
.filter(w -> w.getColour() == RED)
.mapToInt(w -> w.getWeight())
.sum();
System.out.println(”Worker thread count = ” + workers.size());
-Djava.util.concurrent.ForkJoinPool.common.parallelism=4
Worker thread count = 5
© Copyright Azul Systems 2016
Common ForkJoinPool
41
Set<String> workers = new ConcurrentSet<String>();
...
worker.stream().forEach(System.out::println);
-Djava.util.concurrent.ForkJoinPool.common.parallelism=4
ForkJoinPool.commonPool-worker-0
ForkJoinPool.commonPool-worker-1
ForkJoinPool.commonPool-worker-2
ForkJoinPool.commonPool-worker-3
main
© Copyright Azul Systems 2016
Parallel Stream Threads
 Invoking thread is also used as worker
 Parallel stream invokes ForkJoin synchronously
– Blocks until work is finished
 Other application threads using parallel stream will be
affected
 Beware IO blocking actions inside stream operartions
 Do NOT nest parallel streams
© Copyright Azul Systems 2016
Parallel Stream Custom Pool Hack
43
ForkJoinPool customPool = new ForkJoinPool(4);
ForkJoinTask<Integer> hackTask = customPool.submit(() -> {
return list.parallelStream()
.peek(w -> workers.add(Thread.currentThread().getName()))
.filter(w -> w.getColour() == RED)
.mapToInt(w -> w.getWeight())
.sum();
});
int sum = hackTask.get();
Worker thread count = 4
© Copyright Azul Systems 2016
Is A Parallel Stream Faster?
 Using a parallel stream guarantees more work
– Setting up fork-join framework is overhead
 This might complete more quickly
 Depends on several factors
– How many elements in the stream (N)
– How long each element takes to process (T)
– Parallel streams improve with N x T
– Operation types
 map(), filter() good
 sort(), distinct() not so good
44
© Copyright Azul Systems 2016
Lambdas And Streams
And JDK 9
© Copyright Azul Systems 2016
Additional APIs
 Optional now has a stream() method
– Returns a stream of one element or an empty stream
 Collectors.flatMapping()
– Returns a Collector that converts a stream from one
type to another by applying a flat mapping function
46
© Copyright Azul Systems 2016
Additional APIs
 Matcher stream support
– Stream<MatchResult> results()
 Scanner stream support
– Stream<MatchResult> findAll(String pattern)
– Stream<MatchResult> findAll(Pattern pattern)
– Stream<String> tokens()
47
© Copyright Azul Systems 2016
Additional Stream Sources
 java.net.NetworkInterface
– Stream<InetAddress> inetAddresses()
– Stream<NetworkInterface> subInterfaces()
– Stream<NetworkInterface> networkInterfaces()
 static
 java.security.PermissionCollection
– Stream<Permission> elementsAsStream()
48
© Copyright Azul Systems 2016
Parallel Support For Files.lines()
 Memory map file for UTF-8, ISO 8859-1, US-ASCII
– Character sets where line feeds easily identifiable
 Efficient splitting of mapped memory region
 Divides approximately in half
– To nearest line feed
49
© Copyright Azul Systems 2016
Parallel Lines Performance
50
© Copyright Azul Systems 2016
Stream takeWhile
 Stream<T> takeWhile(Predicate<? super T> p)
 Select elements from stream until Predicate matches
 Unordered stream needs consideration
thermalReader.lines()
.mapToInt(i -> Integer.parseInt(i))
.takeWhile(i -> i < 56)
.forEach(System.out::println);
© Copyright Azul Systems 2016
Stream dropWhile
 Stream<T> dropWhile(Predicate<? super T> p)
 Ignore elements from stream until Predicate matches
 Unordered stream still needs consideration
thermalReader.lines()
.mapToInt(i -> Integer.parseInt(i))
.dropWhile(i -> i < 56)
.forEach(System.out::println);
© Copyright Azul Systems 2016
Conclusions
© Copyright Azul Systems 2016
Conclusions
 Lambdas and Stream are a very powerful combination
 Does require developers to think differently
– Avoid loops, even non-obvious ones!
– Reductions
 Be careful with parallel streams
 More to come in JDK 9 (and 10)
 Join the Zulu.org community
– www.zulu.org
54
© Copyright Azul Systems 2016
© Copyright Azul Systems 2015
@speakjava
Q & A
Simon Ritter
Deputy CTO, Azul Systems
55

Mais conteúdo relacionado

Mais procurados

Streams: The Good, The Bad And The Ugly
Streams: The Good, The Bad And The UglyStreams: The Good, The Bad And The Ugly
Streams: The Good, The Bad And The UglySimon Ritter
 
It's Java, Jim, but not as we know it
It's Java, Jim, but not as we know itIt's Java, Jim, but not as we know it
It's Java, Jim, but not as we know itSimon Ritter
 
Whats New For Developers In JDK 9
Whats New For Developers In JDK 9Whats New For Developers In JDK 9
Whats New For Developers In JDK 9Simon Ritter
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8Martin Toshev
 
Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8Ganesh Samarthyam
 
JDK 14 Lots of New Features
JDK 14 Lots of New FeaturesJDK 14 Lots of New Features
JDK 14 Lots of New FeaturesSimon Ritter
 
Functional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting LambdasFunctional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting LambdasGanesh Samarthyam
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8Knoldus Inc.
 
Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Ganesh Samarthyam
 
Modern Programming in Java 8 - Lambdas, Streams and Date Time API
Modern Programming in Java 8 - Lambdas, Streams and Date Time APIModern Programming in Java 8 - Lambdas, Streams and Date Time API
Modern Programming in Java 8 - Lambdas, Streams and Date Time APIGanesh Samarthyam
 

Mais procurados (20)

Streams: The Good, The Bad And The Ugly
Streams: The Good, The Bad And The UglyStreams: The Good, The Bad And The Ugly
Streams: The Good, The Bad And The Ugly
 
Java SE 8
Java SE 8Java SE 8
Java SE 8
 
It's Java, Jim, but not as we know it
It's Java, Jim, but not as we know itIt's Java, Jim, but not as we know it
It's Java, Jim, but not as we know it
 
Whats New For Developers In JDK 9
Whats New For Developers In JDK 9Whats New For Developers In JDK 9
Whats New For Developers In JDK 9
 
Introduction to new features in java 8
Introduction to new features in java 8Introduction to new features in java 8
Introduction to new features in java 8
 
Java 8 Features
Java 8 FeaturesJava 8 Features
Java 8 Features
 
Java SE 8 library design
Java SE 8 library designJava SE 8 library design
Java SE 8 library design
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
 
Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8
 
Java SE 8 best practices
Java SE 8 best practicesJava SE 8 best practices
Java SE 8 best practices
 
JDK 14 Lots of New Features
JDK 14 Lots of New FeaturesJDK 14 Lots of New Features
JDK 14 Lots of New Features
 
Java 8: the good parts!
Java 8: the good parts!Java 8: the good parts!
Java 8: the good parts!
 
Java 8 Feature Preview
Java 8 Feature PreviewJava 8 Feature Preview
Java 8 Feature Preview
 
Functional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting LambdasFunctional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting Lambdas
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8
 
Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams
 
Modern Programming in Java 8 - Lambdas, Streams and Date Time API
Modern Programming in Java 8 - Lambdas, Streams and Date Time APIModern Programming in Java 8 - Lambdas, Streams and Date Time API
Modern Programming in Java 8 - Lambdas, Streams and Date Time API
 
Java 8 streams
Java 8 streamsJava 8 streams
Java 8 streams
 
Streams in Java 8
Streams in Java 8Streams in Java 8
Streams in Java 8
 
Java8
Java8Java8
Java8
 

Destaque

55 New Features in JDK 9
55 New Features in JDK 955 New Features in JDK 9
55 New Features in JDK 9Simon Ritter
 
Is An Agile Standard Possible For Java?
Is An Agile Standard Possible For Java?Is An Agile Standard Possible For Java?
Is An Agile Standard Possible For Java?Simon Ritter
 
JDK 9: Big Changes To Make Java Smaller
JDK 9: Big Changes To Make Java SmallerJDK 9: Big Changes To Make Java Smaller
JDK 9: Big Changes To Make Java SmallerSimon Ritter
 
Project Jigsaw in JDK9
Project Jigsaw in JDK9Project Jigsaw in JDK9
Project Jigsaw in JDK9Simon Ritter
 
JDK 9: Big Changes To Make Java Smaller
JDK 9: Big Changes To Make Java SmallerJDK 9: Big Changes To Make Java Smaller
JDK 9: Big Changes To Make Java SmallerSimon Ritter
 
Teaching kids how to program
Teaching kids how to programTeaching kids how to program
Teaching kids how to programArun Gupta
 
Improved Developer Productivity In JDK8
Improved Developer Productivity In JDK8Improved Developer Productivity In JDK8
Improved Developer Productivity In JDK8Simon Ritter
 
Oracle Keynote from JMagghreb 2014
Oracle Keynote from JMagghreb 2014Oracle Keynote from JMagghreb 2014
Oracle Keynote from JMagghreb 2014Simon Ritter
 
Building microservices with vert.x 3.0
Building microservices with vert.x 3.0Building microservices with vert.x 3.0
Building microservices with vert.x 3.0Agraj Mangal
 
Modularization With Project Jigsaw in JDK 9
Modularization With Project Jigsaw in JDK 9Modularization With Project Jigsaw in JDK 9
Modularization With Project Jigsaw in JDK 9Simon Ritter
 
AppDynamics VS New Relic – The Complete Guide
AppDynamics VS New Relic – The Complete GuideAppDynamics VS New Relic – The Complete Guide
AppDynamics VS New Relic – The Complete GuideTakipi
 
Java 9 and the impact on Maven Projects (JavaOne 2016)
Java 9 and the impact on Maven Projects (JavaOne 2016)Java 9 and the impact on Maven Projects (JavaOne 2016)
Java 9 and the impact on Maven Projects (JavaOne 2016)Robert Scholte
 

Destaque (14)

55 New Features in JDK 9
55 New Features in JDK 955 New Features in JDK 9
55 New Features in JDK 9
 
Is An Agile Standard Possible For Java?
Is An Agile Standard Possible For Java?Is An Agile Standard Possible For Java?
Is An Agile Standard Possible For Java?
 
JDK 9: Big Changes To Make Java Smaller
JDK 9: Big Changes To Make Java SmallerJDK 9: Big Changes To Make Java Smaller
JDK 9: Big Changes To Make Java Smaller
 
Project Jigsaw in JDK9
Project Jigsaw in JDK9Project Jigsaw in JDK9
Project Jigsaw in JDK9
 
JDK 9: Big Changes To Make Java Smaller
JDK 9: Big Changes To Make Java SmallerJDK 9: Big Changes To Make Java Smaller
JDK 9: Big Changes To Make Java Smaller
 
Teaching kids how to program
Teaching kids how to programTeaching kids how to program
Teaching kids how to program
 
The Java Carputer
The Java CarputerThe Java Carputer
The Java Carputer
 
Improved Developer Productivity In JDK8
Improved Developer Productivity In JDK8Improved Developer Productivity In JDK8
Improved Developer Productivity In JDK8
 
Oracle Keynote from JMagghreb 2014
Oracle Keynote from JMagghreb 2014Oracle Keynote from JMagghreb 2014
Oracle Keynote from JMagghreb 2014
 
Building microservices with vert.x 3.0
Building microservices with vert.x 3.0Building microservices with vert.x 3.0
Building microservices with vert.x 3.0
 
Modularization With Project Jigsaw in JDK 9
Modularization With Project Jigsaw in JDK 9Modularization With Project Jigsaw in JDK 9
Modularization With Project Jigsaw in JDK 9
 
AppDynamics VS New Relic – The Complete Guide
AppDynamics VS New Relic – The Complete GuideAppDynamics VS New Relic – The Complete Guide
AppDynamics VS New Relic – The Complete Guide
 
Java 9 and the impact on Maven Projects (JavaOne 2016)
Java 9 and the impact on Maven Projects (JavaOne 2016)Java 9 and the impact on Maven Projects (JavaOne 2016)
Java 9 and the impact on Maven Projects (JavaOne 2016)
 
55 New Features in Java 7
55 New Features in Java 755 New Features in Java 7
55 New Features in Java 7
 

Semelhante a Lessons Learnt With Lambdas and Streams in JDK 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 useSharon Rozinsky
 
A Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its APIA Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its APIJörn Guy Süß JGS
 
Stack squeues lists
Stack squeues listsStack squeues lists
Stack squeues listsJames Wong
 
Stacksqueueslists
StacksqueueslistsStacksqueueslists
StacksqueueslistsFraboni Ec
 
Stacks queues lists
Stacks queues listsStacks queues lists
Stacks queues listsYoung Alista
 
Stacks queues lists
Stacks queues listsStacks queues lists
Stacks queues listsTony Nguyen
 
Stacks queues lists
Stacks queues listsStacks queues lists
Stacks queues listsHarry Potter
 
Intro to Reactive Thinking and RxJava 2
Intro to Reactive Thinking and RxJava 2Intro to Reactive Thinking and RxJava 2
Intro to Reactive Thinking and RxJava 2JollyRogers5
 
Matlab Functions
Matlab FunctionsMatlab Functions
Matlab FunctionsUmer Azeem
 
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
 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 itiAhmed mar3y
 
Data Structures and Algorithms Lecture 2: Analysis of Algorithms, Asymptotic ...
Data Structures and Algorithms Lecture 2: Analysis of Algorithms, Asymptotic ...Data Structures and Algorithms Lecture 2: Analysis of Algorithms, Asymptotic ...
Data Structures and Algorithms Lecture 2: Analysis of Algorithms, Asymptotic ...TechVision8
 
Apache Flink: API, runtime, and project roadmap
Apache Flink: API, runtime, and project roadmapApache Flink: API, runtime, and project roadmap
Apache Flink: API, runtime, and project roadmapKostas Tzoumas
 
Hierarchical free monads and software design in fp
Hierarchical free monads and software design in fpHierarchical free monads and software design in fp
Hierarchical free monads and software design in fpAlexander Granin
 

Semelhante a Lessons Learnt With Lambdas and Streams in JDK 8 (20)

Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Major Java 8 features
Major Java 8 featuresMajor Java 8 features
Major Java 8 features
 
Lambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter LawreyLambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter Lawrey
 
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
 
A Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its APIA Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its API
 
Stack squeues lists
Stack squeues listsStack squeues lists
Stack squeues lists
 
Stacks queues lists
Stacks queues listsStacks queues lists
Stacks queues lists
 
Stacksqueueslists
StacksqueueslistsStacksqueueslists
Stacksqueueslists
 
Stacks queues lists
Stacks queues listsStacks queues lists
Stacks queues lists
 
Stacks queues lists
Stacks queues listsStacks queues lists
Stacks queues lists
 
Stacks queues lists
Stacks queues listsStacks queues lists
Stacks queues lists
 
Intro to Reactive Thinking and RxJava 2
Intro to Reactive Thinking and RxJava 2Intro to Reactive Thinking and RxJava 2
Intro to Reactive Thinking and RxJava 2
 
java8
java8java8
java8
 
Matlab Functions
Matlab FunctionsMatlab Functions
Matlab Functions
 
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
 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 iti
 
Data Structures and Algorithms Lecture 2: Analysis of Algorithms, Asymptotic ...
Data Structures and Algorithms Lecture 2: Analysis of Algorithms, Asymptotic ...Data Structures and Algorithms Lecture 2: Analysis of Algorithms, Asymptotic ...
Data Structures and Algorithms Lecture 2: Analysis of Algorithms, Asymptotic ...
 
Apache Flink: API, runtime, and project roadmap
Apache Flink: API, runtime, and project roadmapApache Flink: API, runtime, and project roadmap
Apache Flink: API, runtime, and project roadmap
 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
 
Hierarchical free monads and software design in fp
Hierarchical free monads and software design in fpHierarchical free monads and software design in fp
Hierarchical free monads and software design in fp
 

Mais de 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
 
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
 

Mais de 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
 
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
 
JDK 9 Deep Dive
JDK 9 Deep DiveJDK 9 Deep Dive
JDK 9 Deep Dive
 

Último

%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...masabamasaba
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...masabamasaba
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareJim McKeeth
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...SelfMade bd
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...masabamasaba
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburgmasabamasaba
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionOnePlan Solutions
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrainmasabamasaba
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfproinshot.com
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesVictorSzoltysek
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsBert Jan Schrijver
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 

Último (20)

%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisions
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 

Lessons Learnt With Lambdas and Streams in JDK 8

  • 1. © Copyright Azul Systems 2016 © Copyright Azul Systems 2015 @speakjava Lessons Learnt With Lambdas and Streams in JDK 8 Simon Ritter Deputy CTO, Azul Systems 1
  • 2. © Copyright Azul Systems 2016 A clever man learns from his mistakes... ...a wise man learns from other people’s
  • 3. © Copyright Azul Systems 2016 Agenda  Lambdas and Streams Primer  Delaying Execution  Avoiding Loops In Streams  The Art Of Reduction  Parallel streams: myths and realities  Lambdas and Streams and JDK 9  Conclusions 3
  • 4. © Copyright Azul Systems 2016 Lambdas And Streams Primer
  • 5. © Copyright Azul Systems 2016 Lambda Expressions In JDK 8  Old style, anonymous inner classes  New style, using a Lambda expression  Can be used wherever the type is a functional interface 5 Simplified Parameterised Behaviour new Thread(new Runnable { public void run() { doSomeStuff(); } }).start(); new Thread(() -> doSomeStuff()).start();
  • 6. © Copyright Azul Systems 2016 Functional Interface Definition  Is an interface  Must have only one abstract method – In JDK 7 this would mean only one method (like ActionListener)  JDK 8 introduced default methods – Adding multiple inheritance of types to Java – These are, by definition, not abstract  JDK 8 also now allows interfaces to have static methods  @FunctionalInterface to have the compiler check 6
  • 7. © Copyright Azul Systems 2016 Type Inference  Compiler can often infer parameter types in a lambda expression – Inferrence based on target functional interface’s method signature  Fully statically typed (no dynamic typing sneaking in) – More typing with less typing static T void sort(List<T> l, Comparator<? super T> c); List<String> list = getList(); Collections.sort(list, (String x, String y) -> x.length() > y.length()); Collections.sort(list, (x, y) -> x.length() - y.length());
  • 8. © Copyright Azul Systems 2016 Stream Overview  A stream pipeline consists of three types of things – A source – Zero or more intermediate operations – A terminal operation  Producing a result or a side-effect int total = transactions.stream() .filter(t -> t.getBuyer().getCity().equals(“London”)) .mapToInt(Transaction::getPrice) .sum(); Source Intermediate operation Terminal operation
  • 9. © Copyright Azul Systems 2016 Stream Terminal Operations  The pipeline is only evaluated when the terminal operation is called – All operations can execute sequentially or in parallel – Intermediate operations can be merged  Avoiding multiple redundant passes on data  Short-circuit operations (e.g. findFirst)  Lazy evaluation – Stream characteristics help identify optimisations  DISTINT stream passed to distinct() is a no-op
  • 10. © Copyright Azul Systems 2016 Optional Class  Terminal operations like min(), max(), etc do not return a direct result – Suppose the input Stream is empty?  Optional<T> – Container for an object reference (null, or real object) – Think of it like a Stream of 0 or 1 elements – use get(), ifPresent() and orElse() to access the stored reference – Can use in more complex ways: filter(), map(), etc
  • 11. © Copyright Azul Systems 2016 Lambda Expressions And Delayed Execution
  • 12. © Copyright Azul Systems 2016 Performance Impact For Logging  Heisenberg’s uncertainty principle  Setting log level to INFO still has a performance impact  Since Logger determines whether to log the message the parameter must be evaluated even when not used 12 logger.finest(getSomeStatusData()); Always executed
  • 13. © Copyright Azul Systems 2016 Supplier<T>  Represents a supplier of results  All relevant logging methods now have a version that takes a Supplier  Pass a description of how to create the log message – Not the message  If the Logger doesn’t need the value it doesn’t invoke the Lambda  Can be used for other conditional activities 13 logger.finest(getSomeStatusData());logger.finest(() -> getSomeStatusData());
  • 14. © Copyright Azul Systems 2016 Avoiding Loops In Streams
  • 15. © Copyright Azul Systems 2016 Functional v. Imperative  For functional programming you should not modify state  Java supports closures over values, not closures over variables  But state is really useful… 15
  • 16. © Copyright Azul Systems 2016 Counting Methods That Return Streams 16 Still Thinking Imperatively Set<String> sourceKeySet = streamReturningMethodMap.keySet(); LongAdder sourceCount = new LongAdder(); sourceKeySet.stream() .forEach(c -> sourceCount .add(streamReturningMethodMap.get(c).size()));
  • 17. © Copyright Azul Systems 2016 Counting Methods That Return Streams 17 Functional Way sourceKeySet.stream() .mapToInt(c -> streamReturningMethodMap.get(c).size()) .sum();
  • 18. © Copyright Azul Systems 2016 Printing And Counting 18 Still Thinking Imperatively LongAdder newMethodCount = new LongAdder(); functionalParameterMethodMap.get(c).stream() .forEach(m -> { output.println(m); if (isNewMethod(c, m)) newMethodCount.increment(); });
  • 19. © Copyright Azul Systems 2016 Printing And Counting 19 More Functional, But Not Pure 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
  • 20. © Copyright Azul Systems 2016 Printing And Counting 20 Even More Functional, But Still Not Pure Functional 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
  • 21. © Copyright Azul Systems 2016 The Art Of Reduction (Or The Need to Think Differently)
  • 22. © Copyright Azul Systems 2016 A Simple Problem  Find the length of the longest line in a file  Hint: BufferedReader has a new method, lines(), that returns a Stream 22 BufferedReader reader = ... int longest = reader.lines() .mapToInt(String::length) .max() .getAsInt();
  • 23. © Copyright Azul Systems 2016 Another Simple Problem  Find the length of the longest line in a file 23
  • 24. © Copyright Azul Systems 2016 Another Simple Problem  Find the length of the longest line in a file 24
  • 25. © Copyright Azul Systems 2016 Naïve Stream Solution  That works, so job done, right?  Not really. Big files will take a long time and a lot of resources  Must be a better approach 25 String longest = reader.lines(). sort((x, y) -> y.length() - x.length()). findFirst(). get();
  • 26. © Copyright Azul Systems 2016 External Iteration Solution  Simple, but inherently serial  Not thread safe due to mutable state 26 String longest = ""; while ((String s = reader.readLine()) != null) if (s.length() > longest.length()) longest = s;
  • 27. © Copyright Azul Systems 2016 Recursive Approach 27 String findLongestString(String longest, BufferedReader reader) { String next = reader.readLine(); if (next == null) return longest; if (next.length() > longest.length()) longest = next; return findLongestString(longest, reader); }
  • 28. © Copyright Azul Systems 2016 Recursion: Solving The Problem  No explicit loop, no mutable state, we’re all good now, right?  Unfortunately not: – larger data sets will generate an OOM exception – Too many stack frames 28 String longest = findLongestString("", reader);
  • 29. © Copyright Azul Systems 2016 A Better Stream Solution  Stream API uses the well known filter-map-reduce pattern  For this problem we do not need to filter or map, just reduce Optional<T> reduce(BinaryOperator<T> accumulator)  BinaryOperator is a subclass of BiFunction – R apply(T t, U u)  For BinaryOperator all types are the same – T apply(T x, T y) 29
  • 30. © Copyright Azul Systems 2016 A Better Stream Solution  The key is to find the right accumulator – The accumulator takes a partial result and the next element, and returns a new partial result – In essence it does the same as our recursive solution – But without all the stack frames 30
  • 31. © Copyright Azul Systems 2016 A Better Stream Solution  Use the recursive approach as an accululator for a reduction 31 String longestLine = reader.lines() .reduce((x, y) -> { if (x.length() > y.length()) return x; return y; }) .get();
  • 32. © Copyright Azul Systems 2016 A Better Stream Solution  Use the recursive approach as an accululator for a reduction 32 String longestLine = reader.lines() .reduce((x, y) -> { if (x.length() > y.length()) return x; return y; }) .get(); x in effect maintains state for us, by providing the partial result, which is the longest string found so far
  • 33. © Copyright Azul Systems 2016 The Simplest Stream Solution  Use a specialised form of max()  One that takes a Comparator as a parameter  comparingInt() is a static method on Comparator Comparator<T> comparingInt( ToIntFunction<? extends T> keyExtractor) 33 reader.lines() .max(comparingInt(String::length)) .get();
  • 34. © Copyright Azul Systems 2016 Parallel Streams: Myths And Realities
  • 35. © Copyright Azul Systems 2016 35
  • 36. © Copyright Azul Systems 2016 Serial And Parallel Streams  Syntactically very simple to change from serial to parallel 36 int sum = list.stream() .filter(w -> w.getColour() == RED) .mapToInt(w -> w.getWeight()) .sum(); int sum = list.parallelStream() .filter(w -> w.getColour() == RED) .mapToInt(w -> w.getWeight()) .sum();
  • 37. © Copyright Azul Systems 2016 Serial And Parallel Streams  Syntactically very simple to change from serial to parallel  Use serial() or parallel() to change mid-stream 37 int sum = list.parallelStream() .filter(w -> w.getColour() == RED) .serial() .mapToInt(w -> w.getWeight()) .parallel() .sum();
  • 38. © Copyright Azul Systems 2016 Serial And Parallel Streams  Syntactically very simple to change from serial to parallel  Use serial() or parallel() to change mid-stream  Whole stream is processed serially or in parallel – Last call wins  Operations should be stateless and independent 38 int sum = list.parallelStream() .filter(w -> w.getColour() == RED) .serial() .mapToInt(w -> w.getWeight()) .parallel() .sum();
  • 39. © Copyright Azul Systems 2016 Common ForkJoinPool  Created when JVM starts up  Default number of threads is equal to CPUs reported by OS – Runtime.getRuntime().availableProcessors()  Can be changed manually 39 -Djava.util.concurrent.ForkJoinPool.common.parallelism=n
  • 40. © Copyright Azul Systems 2016 Common ForkJoinPool 40 Set<String> workers = new ConcurrentSet<String>(); int sum = list.parallelStream() .peek(n -> workers.add(Thread.currentThread().getName())) .filter(w -> w.getColour() == RED) .mapToInt(w -> w.getWeight()) .sum(); System.out.println(”Worker thread count = ” + workers.size()); -Djava.util.concurrent.ForkJoinPool.common.parallelism=4 Worker thread count = 5
  • 41. © Copyright Azul Systems 2016 Common ForkJoinPool 41 Set<String> workers = new ConcurrentSet<String>(); ... worker.stream().forEach(System.out::println); -Djava.util.concurrent.ForkJoinPool.common.parallelism=4 ForkJoinPool.commonPool-worker-0 ForkJoinPool.commonPool-worker-1 ForkJoinPool.commonPool-worker-2 ForkJoinPool.commonPool-worker-3 main
  • 42. © Copyright Azul Systems 2016 Parallel Stream Threads  Invoking thread is also used as worker  Parallel stream invokes ForkJoin synchronously – Blocks until work is finished  Other application threads using parallel stream will be affected  Beware IO blocking actions inside stream operartions  Do NOT nest parallel streams
  • 43. © Copyright Azul Systems 2016 Parallel Stream Custom Pool Hack 43 ForkJoinPool customPool = new ForkJoinPool(4); ForkJoinTask<Integer> hackTask = customPool.submit(() -> { return list.parallelStream() .peek(w -> workers.add(Thread.currentThread().getName())) .filter(w -> w.getColour() == RED) .mapToInt(w -> w.getWeight()) .sum(); }); int sum = hackTask.get(); Worker thread count = 4
  • 44. © Copyright Azul Systems 2016 Is A Parallel Stream Faster?  Using a parallel stream guarantees more work – Setting up fork-join framework is overhead  This might complete more quickly  Depends on several factors – How many elements in the stream (N) – How long each element takes to process (T) – Parallel streams improve with N x T – Operation types  map(), filter() good  sort(), distinct() not so good 44
  • 45. © Copyright Azul Systems 2016 Lambdas And Streams And JDK 9
  • 46. © Copyright Azul Systems 2016 Additional APIs  Optional now has a stream() method – Returns a stream of one element or an empty stream  Collectors.flatMapping() – Returns a Collector that converts a stream from one type to another by applying a flat mapping function 46
  • 47. © Copyright Azul Systems 2016 Additional APIs  Matcher stream support – Stream<MatchResult> results()  Scanner stream support – Stream<MatchResult> findAll(String pattern) – Stream<MatchResult> findAll(Pattern pattern) – Stream<String> tokens() 47
  • 48. © Copyright Azul Systems 2016 Additional Stream Sources  java.net.NetworkInterface – Stream<InetAddress> inetAddresses() – Stream<NetworkInterface> subInterfaces() – Stream<NetworkInterface> networkInterfaces()  static  java.security.PermissionCollection – Stream<Permission> elementsAsStream() 48
  • 49. © Copyright Azul Systems 2016 Parallel Support For Files.lines()  Memory map file for UTF-8, ISO 8859-1, US-ASCII – Character sets where line feeds easily identifiable  Efficient splitting of mapped memory region  Divides approximately in half – To nearest line feed 49
  • 50. © Copyright Azul Systems 2016 Parallel Lines Performance 50
  • 51. © Copyright Azul Systems 2016 Stream takeWhile  Stream<T> takeWhile(Predicate<? super T> p)  Select elements from stream until Predicate matches  Unordered stream needs consideration thermalReader.lines() .mapToInt(i -> Integer.parseInt(i)) .takeWhile(i -> i < 56) .forEach(System.out::println);
  • 52. © Copyright Azul Systems 2016 Stream dropWhile  Stream<T> dropWhile(Predicate<? super T> p)  Ignore elements from stream until Predicate matches  Unordered stream still needs consideration thermalReader.lines() .mapToInt(i -> Integer.parseInt(i)) .dropWhile(i -> i < 56) .forEach(System.out::println);
  • 53. © Copyright Azul Systems 2016 Conclusions
  • 54. © Copyright Azul Systems 2016 Conclusions  Lambdas and Stream are a very powerful combination  Does require developers to think differently – Avoid loops, even non-obvious ones! – Reductions  Be careful with parallel streams  More to come in JDK 9 (and 10)  Join the Zulu.org community – www.zulu.org 54
  • 55. © Copyright Azul Systems 2016 © Copyright Azul Systems 2015 @speakjava Q & A Simon Ritter Deputy CTO, Azul Systems 55