SlideShare a Scribd company logo
1 of 44
Lambda Expressions In JDK8
Going Beyond The Basics
Simon Ritter
Head of Java Technology Evangelism
Oracle Corp.
Twitter: @speakjava
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Safe Harbor Statement
The following is intended to outline our general product direction. It is intended for
information purposes only, and may not be incorporated into any contract. It is not a
commitment to deliver any material, code, or functionality, and should not be relied upon
in making purchasing decisions. The development, release, and timing of any features or
functionality described for Oracle’s products remains at the sole discretion of Oracle.
2
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Program Agenda
Lambdas And Streams Primer
Delaying Execution
Avoiding loops in Streams
The Art of Reduction
Conclusions
1
2
3
4
5
Oracle Confidential – Internal/Restricted/Highly Restricted 3
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Lambdas And Streams Primer
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Lambda Expressions In JDK8
• Old style, anonymous inner classes
• New style, using a Lambda expression
5
Simplified Parameterised Behaviour
new Thread(new Runnable {
public void run() {
doSomeStuff();
}
}).start();
new Thread(() -> doSomeStuff()).start();
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Lambda Expressions
• Lambda expressions represent anonymous functions
– Same structure as a method
• typed argument list, return type, set of thrown exceptions, and a body
– Not associated with a class
• We now have parameterised behaviour, not just values
Some Details
double highestScore = students.
filter(Student s -> s.getGradYear() == 2011).
map(Student s -> s.getScore())
max();
What
How
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Lambda Expression Types
• Single-method interfaces are used extensively in Java
– Definition: a functional interface is an interface with one abstract method
– Functional interfaces are identified structurally
– The type of a lambda expression will be a functional interface
• Lambda expressions provide implementations of the abstract method
interface Comparator<T> { boolean compare(T x, T y); }
interface FileFilter { boolean accept(File x); }
interface Runnable { void run(); }
interface ActionListener { void actionPerformed(…); }
interface Callable<T> { T call(); }
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Local Variable Capture
• Lambda expressions can refer to effectively final local variables from the
surrounding scope
– Effectively final: A variable that meets the requirements for final variables (i.e.,
assigned once), even if not explicitly declared final
– Closures on values, not variables
void expire(File root, long before) {
root.listFiles(File p -> p.lastModified() <= before);
}
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
What Does ‘this’ Mean In A Lambda
• ‘this’ refers to the enclosing object, not the lambda itself
• Think of ‘this’ as a final predefined local
• Remember the Lambda is an anonymous function
– It is not associated with a class
– Therefore there can be no ‘this’ for the Lambda
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Referencing Instance Variables
Which are not final, or effectively final
class DataProcessor {
private int currentValue;
public void process() {
DataSet myData = myFactory.getDataSet();
dataSet.forEach(d -> d.use(currentValue++));
}
}
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Referencing Instance Variables
The compiler helps us out
class DataProcessor {
private int currentValue;
public void process() {
DataSet myData = myFactory.getDataSet();
dataSet.forEach(d -> d.use(this.currentValue++);
}
}
‘this’ (which is effectively final)
inserted by the compiler
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Type Inference
• The compiler can often infer parameter types in a lambda expression
 Inferrence based on the target functional interface’s method signature
• Fully statically typed (no dynamic typing sneaking in)
– More typing with less typing
List<String> list = getList();
Collections.sort(list, (String x, String y) -> x.length() - y.length());
Collections.sort(list, (x, y) -> x.length() - y.length());
static T void sort(List<T> l, Comparator<? super T> c);
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Functional Interface Definition
• 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 (they have an implementation)
• JDK 8 also now allows interfaces to have static methods
– Again, not abstract
• @FunctionalInterface can be used to have the compiler check
13
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Is This A Functional Interface?
14
@FunctionalInterface
public interface Runnable {
public abstract void run();
}
Yes. There is only
one abstract method
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Is This A Functional Interface?
15
@FunctionalInterface
public interface Predicate<T> {
default Predicate<T> and(Predicate<? super T> p) {…};
default Predicate<T> negate() {…};
default Predicate<T> or(Predicate<? super T> p) {…};
static <T> Predicate<T> isEqual(Object target) {…};
boolean test(T t);
}
Yes. There is still only
one abstract method
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Is This A Functional Interface?
16
@FunctionalInterface
public interface Comparator {
// Static and default methods elided
int compare(T o1, T o2);
boolean equals(Object obj);
}
The equals(Object)
method is implicit from
the Object class
Therefore only one
abstract method
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
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
Pipeline
int total = transactions.stream()
.filter(t -> t.getBuyer().getCity().equals(“London”))
.mapToInt(Transaction::getPrice)
.sum();
Source
Intermediate operation
Terminal operation
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Stream Sources
• From collections and arrays
– Collection.stream()
– Collection.parallelStream()
– Arrays.stream(T array) or Stream.of()
• Static factories
– IntStream.range()
– Files.walk()
• Roll your own
– java.util.Spliterator
Many Ways To Create
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
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
• gpsMaybe.filter(r -> r.lastReading() < 2).ifPresent(GPSData::display);
Helping To Eliminate the NullPointerException
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Lambda Expressions and
Delayed Execution
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
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
22
logger.finest(getSomeStatusData());
Always executed
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
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
23
logger.finest(() -> getSomeStatusData());
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Avoiding Loops In Streams
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
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…
25
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Counting Methods That Return Streams
26
Still Thinking Impaeratively Way
Set<String> sourceKeySet = streamReturningMethodMap.keySet();
LongAdder sourceCount = new LongAdder();
sourceKeySet.stream()
.forEach(c ->
sourceCount.add(streamReturningMethodMap.get(c).size()));
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Counting Methods That Return Streams
27
Functional Way
sourceKeySet.stream()
.mapToInt(c -> streamReturningMethodMap.get(c).size())
.sum();
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Printing And Counting Functional Interfaces
28
Still Thinking Imperatively Way
LongAdder newMethodCount = new LongAdder();
functionalParameterMethodMap.get(c).stream()
.forEach(m -> {
output.println(m);
if (isNewMethod(c, m))
newMethodCount.increment();
});
return newMethodCount.intValue();
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Printing And Counting Functional Interfaces
29
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 © 2014, Oracle and/or its affiliates. All rights reserved.
Printing And Counting Functional Interfaces
30
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 © 2014, Oracle and/or its affiliates. All rights reserved.
The Art Of Reduction
(Or The Need to Think Differently)
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
A Simple Problem
• Find the length of the longest line in a file
• Hint: BufferedReader has a new method, lines(), that returns a Stream
32
BufferedReader reader = ...
reader.lines()
.mapToInt(String::length)
.max()
.getAsInt();
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Another Simple Problem
• Find the length of the longest line in a file
33
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
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
34
String longest = reader.lines().
sort((x, y) -> y.length() - x.length()).
findFirst().
get();
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
External Iteration Solution
• Simple, but inherently serial
• Not thread safe due to mutable state
35
String longest = "";
while ((String s = reader.readLine()) != null)
if (s.length() > longest.length())
longest = s;
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Recursive Approach: The Method
36
String findLongestString(String s, int index, List<String> l) {
if (index == l.size() - 1) {
if (s.length() > l.get(index).length())
return s;
return l.get(index);
}
String s2 = findLongestString(l.get(start), index + 1, l);
if (s.length() > s2.length())
return s;
return s2;
}
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Recursive Approach: 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
37
List<String> lines = new ArrayList<>();
while ((String s = reader.readLine()) != null)
lines.add(s);
String longest = findLongestString("", 0, lines);
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
A Better Stream Solution
• The 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, but all types are the same
• R apply(T t, U u) or T apply(T x, T y)
38
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
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 back to front
– And without all the stack frames or List overhead
39
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
A Better Stream Solution
• Use the recursive approach as an accululator for a reduction
40
String longestLine = reader.lines()
.reduce((x, y) -> {
if (x.length() > y.length())
return x;
return y;
})
.get();
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
A Better Stream Solution
• Use the recursive approach as an accululator for a reduction
41
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 © 2014, Oracle and/or its affiliates. All rights reserved.
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)
42
reader.lines()
.max(comparingInt(String::length))
.get();
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Conclusions
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Conclusions
• Lambdas provide a simple way to parameterise behaviour
• The Stream API provides a functional style of programming
• Very powerful combination
• Does require developers to think differently
• Avoid loops, even non-obvious ones!
44
Simon Ritter
Oracle Corporartion
Twitter: @speakjava
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

More Related Content

What's hot

Lambdas Hands On Lab
Lambdas Hands On LabLambdas Hands On Lab
Lambdas Hands On LabSimon Ritter
 
Functional Programming With Lambdas and Streams in JDK8
 Functional Programming With Lambdas and Streams in JDK8 Functional Programming With Lambdas and Streams in JDK8
Functional Programming With Lambdas and Streams in JDK8IndicThreads
 
Lessons Learnt With Lambdas and Streams in JDK 8
Lessons Learnt With Lambdas and Streams in JDK 8Lessons Learnt With Lambdas and Streams in JDK 8
Lessons Learnt With Lambdas and Streams in JDK 8Simon Ritter
 
55 New Features in Java SE 8
55 New Features in Java SE 855 New Features in Java SE 8
55 New Features in Java SE 8Simon Ritter
 
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
 
Java SE 8 - New Features
Java SE 8 - New FeaturesJava SE 8 - New Features
Java SE 8 - New FeaturesNaveen Hegde
 
Whats New in Java 5, 6, & 7 (Webinar Presentation - June 2013)
Whats New in Java 5, 6, & 7 (Webinar Presentation - June 2013)Whats New in Java 5, 6, & 7 (Webinar Presentation - June 2013)
Whats New in Java 5, 6, & 7 (Webinar Presentation - June 2013)DevelopIntelligence
 
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and StreamsIntroduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and StreamsEmiel Paasschens
 
Lambdas & Streams
Lambdas & StreamsLambdas & Streams
Lambdas & StreamsC4Media
 
The Dark Side Of Lambda Expressions in Java 8
The Dark Side Of Lambda Expressions in Java 8The Dark Side Of Lambda Expressions in Java 8
The Dark Side Of Lambda Expressions in Java 8Takipi
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features OverviewSergii Stets
 

What's hot (20)

Lambdas Hands On Lab
Lambdas Hands On LabLambdas Hands On Lab
Lambdas Hands On Lab
 
Functional Programming With Lambdas and Streams in JDK8
 Functional Programming With Lambdas and Streams in JDK8 Functional Programming With Lambdas and Streams in JDK8
Functional Programming With Lambdas and Streams in JDK8
 
Lessons Learnt With Lambdas and Streams in JDK 8
Lessons Learnt With Lambdas and Streams in JDK 8Lessons Learnt With Lambdas and Streams in JDK 8
Lessons Learnt With Lambdas and Streams in JDK 8
 
55 New Features in Java SE 8
55 New Features in Java SE 855 New Features in Java SE 8
55 New Features in Java SE 8
 
Apouc 2014-java-8-create-the-future
Apouc 2014-java-8-create-the-futureApouc 2014-java-8-create-the-future
Apouc 2014-java-8-create-the-future
 
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
 
The Java Carputer
The Java CarputerThe Java Carputer
The Java Carputer
 
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 SE 8 library design
Java SE 8 library designJava SE 8 library design
Java SE 8 library design
 
Java 8 Features
Java 8 FeaturesJava 8 Features
Java 8 Features
 
Java 8 Features
Java 8 FeaturesJava 8 Features
Java 8 Features
 
Java SE 8 - New Features
Java SE 8 - New FeaturesJava SE 8 - New Features
Java SE 8 - New Features
 
Java SE 8 best practices
Java SE 8 best practicesJava SE 8 best practices
Java SE 8 best practices
 
Whats New in Java 5, 6, & 7 (Webinar Presentation - June 2013)
Whats New in Java 5, 6, & 7 (Webinar Presentation - June 2013)Whats New in Java 5, 6, & 7 (Webinar Presentation - June 2013)
Whats New in Java 5, 6, & 7 (Webinar Presentation - June 2013)
 
JDK8 Streams
JDK8 StreamsJDK8 Streams
JDK8 Streams
 
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and StreamsIntroduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
 
Lambdas & Streams
Lambdas & StreamsLambdas & Streams
Lambdas & Streams
 
Java 8
Java 8Java 8
Java 8
 
The Dark Side Of Lambda Expressions in Java 8
The Dark Side Of Lambda Expressions in Java 8The Dark Side Of Lambda Expressions in Java 8
The Dark Side Of Lambda Expressions in Java 8
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features Overview
 

Similar to Lambdas : Beyond The Basics

Lambdas And Streams in JDK8
Lambdas And Streams in JDK8Lambdas And Streams in JDK8
Lambdas And Streams in JDK8Simon Ritter
 
Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...
Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...
Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...jaxLondonConference
 
What's New in Java 8
What's New in Java 8What's New in Java 8
What's New in Java 8javafxpert
 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project LambdaRahman USTA
 
JShell: An Interactive Shell for the Java Platform
JShell: An Interactive Shell for the Java PlatformJShell: An Interactive Shell for the Java Platform
JShell: An Interactive Shell for the Java PlatformJavaDayUA
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streamsjessitron
 
Interactive Java Support to your tool -- The JShell API and Architecture
Interactive Java Support to your tool -- The JShell API and ArchitectureInteractive Java Support to your tool -- The JShell API and Architecture
Interactive Java Support to your tool -- The JShell API and ArchitectureJavaDayUA
 
Functional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singhFunctional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singhHarmeet Singh(Taara)
 
Automatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to InterfacesAutomatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to InterfacesRaffi Khatchadourian
 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 itiAhmed mar3y
 
Servlet 4.0 Adopt-a-JSR 10 Minute Infodeck
Servlet 4.0 Adopt-a-JSR 10 Minute InfodeckServlet 4.0 Adopt-a-JSR 10 Minute Infodeck
Servlet 4.0 Adopt-a-JSR 10 Minute InfodeckEdward Burns
 
JAX-RS 2.0: RESTful Web Services
JAX-RS 2.0: RESTful Web ServicesJAX-RS 2.0: RESTful Web Services
JAX-RS 2.0: RESTful Web ServicesArun Gupta
 
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...Raffi Khatchadourian
 

Similar to Lambdas : Beyond The Basics (20)

Lambdas And Streams in JDK8
Lambdas And Streams in JDK8Lambdas And Streams in JDK8
Lambdas And Streams in JDK8
 
Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...
Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...
Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...
 
What's New in Java 8
What's New in Java 8What's New in Java 8
What's New in Java 8
 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project Lambda
 
Lambdas and Laughs
Lambdas and LaughsLambdas and Laughs
Lambdas and Laughs
 
Java 8 Feature Preview
Java 8 Feature PreviewJava 8 Feature Preview
Java 8 Feature Preview
 
Completable future
Completable futureCompletable future
Completable future
 
JShell: An Interactive Shell for the Java Platform
JShell: An Interactive Shell for the Java PlatformJShell: An Interactive Shell for the Java Platform
JShell: An Interactive Shell for the Java Platform
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streams
 
Java 8 streams
Java 8 streams Java 8 streams
Java 8 streams
 
Interactive Java Support to your tool -- The JShell API and Architecture
Interactive Java Support to your tool -- The JShell API and ArchitectureInteractive Java Support to your tool -- The JShell API and Architecture
Interactive Java Support to your tool -- The JShell API and Architecture
 
Functional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singhFunctional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singh
 
Automatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to InterfacesAutomatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to Interfaces
 
Java8
Java8Java8
Java8
 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 iti
 
Servlet 4.0 Adopt-a-JSR 10 Minute Infodeck
Servlet 4.0 Adopt-a-JSR 10 Minute InfodeckServlet 4.0 Adopt-a-JSR 10 Minute Infodeck
Servlet 4.0 Adopt-a-JSR 10 Minute Infodeck
 
JAX-RS 2.0: RESTful Web Services
JAX-RS 2.0: RESTful Web ServicesJAX-RS 2.0: RESTful Web Services
JAX-RS 2.0: RESTful Web Services
 
Java 8 new features
Java 8 new featuresJava 8 new features
Java 8 new features
 
What`s New in Java 8
What`s New in Java 8What`s New in Java 8
What`s New in Java 8
 
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
 

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

What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesVictoriaMetrics
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogueitservices996
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITmanoharjgpsolutions
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...OnePlan Solutions
 
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
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxRTS corp
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shardsChristopher Curtin
 
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jGraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jNeo4j
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonApplitools
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsJean Silva
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldRoberto Pérez Alcolea
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorTier1 app
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...Bert Jan Schrijver
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?Alexandre Beguel
 
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdfAndrey Devyatkin
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingShane Coughlan
 

Recently uploaded (20)

What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 Updates
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogue
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh IT
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
 
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
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards
 
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jGraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero results
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository world
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryError
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?
 
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
 

Lambdas : Beyond The Basics

  • 1. Lambda Expressions In JDK8 Going Beyond The Basics Simon Ritter Head of Java Technology Evangelism Oracle Corp. Twitter: @speakjava Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  • 2. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Safe Harbor Statement The following is intended to outline our general product direction. It is intended for information purposes only, and may not be incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions. The development, release, and timing of any features or functionality described for Oracle’s products remains at the sole discretion of Oracle. 2
  • 3. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Program Agenda Lambdas And Streams Primer Delaying Execution Avoiding loops in Streams The Art of Reduction Conclusions 1 2 3 4 5 Oracle Confidential – Internal/Restricted/Highly Restricted 3
  • 4. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Lambdas And Streams Primer
  • 5. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Lambda Expressions In JDK8 • Old style, anonymous inner classes • New style, using a Lambda expression 5 Simplified Parameterised Behaviour new Thread(new Runnable { public void run() { doSomeStuff(); } }).start(); new Thread(() -> doSomeStuff()).start();
  • 6. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Lambda Expressions • Lambda expressions represent anonymous functions – Same structure as a method • typed argument list, return type, set of thrown exceptions, and a body – Not associated with a class • We now have parameterised behaviour, not just values Some Details double highestScore = students. filter(Student s -> s.getGradYear() == 2011). map(Student s -> s.getScore()) max(); What How
  • 7. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Lambda Expression Types • Single-method interfaces are used extensively in Java – Definition: a functional interface is an interface with one abstract method – Functional interfaces are identified structurally – The type of a lambda expression will be a functional interface • Lambda expressions provide implementations of the abstract method interface Comparator<T> { boolean compare(T x, T y); } interface FileFilter { boolean accept(File x); } interface Runnable { void run(); } interface ActionListener { void actionPerformed(…); } interface Callable<T> { T call(); }
  • 8. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Local Variable Capture • Lambda expressions can refer to effectively final local variables from the surrounding scope – Effectively final: A variable that meets the requirements for final variables (i.e., assigned once), even if not explicitly declared final – Closures on values, not variables void expire(File root, long before) { root.listFiles(File p -> p.lastModified() <= before); }
  • 9. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. What Does ‘this’ Mean In A Lambda • ‘this’ refers to the enclosing object, not the lambda itself • Think of ‘this’ as a final predefined local • Remember the Lambda is an anonymous function – It is not associated with a class – Therefore there can be no ‘this’ for the Lambda
  • 10. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Referencing Instance Variables Which are not final, or effectively final class DataProcessor { private int currentValue; public void process() { DataSet myData = myFactory.getDataSet(); dataSet.forEach(d -> d.use(currentValue++)); } }
  • 11. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Referencing Instance Variables The compiler helps us out class DataProcessor { private int currentValue; public void process() { DataSet myData = myFactory.getDataSet(); dataSet.forEach(d -> d.use(this.currentValue++); } } ‘this’ (which is effectively final) inserted by the compiler
  • 12. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Type Inference • The compiler can often infer parameter types in a lambda expression  Inferrence based on the target functional interface’s method signature • Fully statically typed (no dynamic typing sneaking in) – More typing with less typing List<String> list = getList(); Collections.sort(list, (String x, String y) -> x.length() - y.length()); Collections.sort(list, (x, y) -> x.length() - y.length()); static T void sort(List<T> l, Comparator<? super T> c);
  • 13. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Functional Interface Definition • 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 (they have an implementation) • JDK 8 also now allows interfaces to have static methods – Again, not abstract • @FunctionalInterface can be used to have the compiler check 13
  • 14. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Is This A Functional Interface? 14 @FunctionalInterface public interface Runnable { public abstract void run(); } Yes. There is only one abstract method
  • 15. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Is This A Functional Interface? 15 @FunctionalInterface public interface Predicate<T> { default Predicate<T> and(Predicate<? super T> p) {…}; default Predicate<T> negate() {…}; default Predicate<T> or(Predicate<? super T> p) {…}; static <T> Predicate<T> isEqual(Object target) {…}; boolean test(T t); } Yes. There is still only one abstract method
  • 16. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Is This A Functional Interface? 16 @FunctionalInterface public interface Comparator { // Static and default methods elided int compare(T o1, T o2); boolean equals(Object obj); } The equals(Object) method is implicit from the Object class Therefore only one abstract method
  • 17. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 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 Pipeline int total = transactions.stream() .filter(t -> t.getBuyer().getCity().equals(“London”)) .mapToInt(Transaction::getPrice) .sum(); Source Intermediate operation Terminal operation
  • 18. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Stream Sources • From collections and arrays – Collection.stream() – Collection.parallelStream() – Arrays.stream(T array) or Stream.of() • Static factories – IntStream.range() – Files.walk() • Roll your own – java.util.Spliterator Many Ways To Create
  • 19. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 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 • gpsMaybe.filter(r -> r.lastReading() < 2).ifPresent(GPSData::display); Helping To Eliminate the NullPointerException
  • 20. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Lambda Expressions and Delayed Execution
  • 21. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 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 22 logger.finest(getSomeStatusData()); Always executed
  • 22. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 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 23 logger.finest(() -> getSomeStatusData());
  • 23. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Avoiding Loops In Streams
  • 24. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 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… 25
  • 25. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Counting Methods That Return Streams 26 Still Thinking Impaeratively Way Set<String> sourceKeySet = streamReturningMethodMap.keySet(); LongAdder sourceCount = new LongAdder(); sourceKeySet.stream() .forEach(c -> sourceCount.add(streamReturningMethodMap.get(c).size()));
  • 26. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Counting Methods That Return Streams 27 Functional Way sourceKeySet.stream() .mapToInt(c -> streamReturningMethodMap.get(c).size()) .sum();
  • 27. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Printing And Counting Functional Interfaces 28 Still Thinking Imperatively Way LongAdder newMethodCount = new LongAdder(); functionalParameterMethodMap.get(c).stream() .forEach(m -> { output.println(m); if (isNewMethod(c, m)) newMethodCount.increment(); }); return newMethodCount.intValue();
  • 28. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Printing And Counting Functional Interfaces 29 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
  • 29. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Printing And Counting Functional Interfaces 30 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
  • 30. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. The Art Of Reduction (Or The Need to Think Differently)
  • 31. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. A Simple Problem • Find the length of the longest line in a file • Hint: BufferedReader has a new method, lines(), that returns a Stream 32 BufferedReader reader = ... reader.lines() .mapToInt(String::length) .max() .getAsInt();
  • 32. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Another Simple Problem • Find the length of the longest line in a file 33
  • 33. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 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 34 String longest = reader.lines(). sort((x, y) -> y.length() - x.length()). findFirst(). get();
  • 34. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. External Iteration Solution • Simple, but inherently serial • Not thread safe due to mutable state 35 String longest = ""; while ((String s = reader.readLine()) != null) if (s.length() > longest.length()) longest = s;
  • 35. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Recursive Approach: The Method 36 String findLongestString(String s, int index, List<String> l) { if (index == l.size() - 1) { if (s.length() > l.get(index).length()) return s; return l.get(index); } String s2 = findLongestString(l.get(start), index + 1, l); if (s.length() > s2.length()) return s; return s2; }
  • 36. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Recursive Approach: 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 37 List<String> lines = new ArrayList<>(); while ((String s = reader.readLine()) != null) lines.add(s); String longest = findLongestString("", 0, lines);
  • 37. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. A Better Stream Solution • The 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, but all types are the same • R apply(T t, U u) or T apply(T x, T y) 38
  • 38. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 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 back to front – And without all the stack frames or List overhead 39
  • 39. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. A Better Stream Solution • Use the recursive approach as an accululator for a reduction 40 String longestLine = reader.lines() .reduce((x, y) -> { if (x.length() > y.length()) return x; return y; }) .get();
  • 40. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. A Better Stream Solution • Use the recursive approach as an accululator for a reduction 41 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
  • 41. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 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) 42 reader.lines() .max(comparingInt(String::length)) .get();
  • 42. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Conclusions
  • 43. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Conclusions • Lambdas provide a simple way to parameterise behaviour • The Stream API provides a functional style of programming • Very powerful combination • Does require developers to think differently • Avoid loops, even non-obvious ones! 44
  • 44. Simon Ritter Oracle Corporartion Twitter: @speakjava Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Editor's Notes

  1. This is a Title Slide with Java FY15 Theme slide ideal for including the Java Theme with a brief title, subtitle and presenter information. To customize this slide with your own picture: Right-click the slide area and choose Format Background from the pop-up menu. From the Fill menu, click Picture and texture fill. Under Insert from: click File. Locate your new picture and click Insert. To copy the Customized Background from Another Presentation on PC Click New Slide from the Home tab's Slides group and select Reuse Slides. Click Browse in the Reuse Slides panel and select Browse Files. Double-click the PowerPoint presentation that contains the background you wish to copy. Check Keep Source Formatting and click the slide that contains the background you want. Click the left-hand slide preview to which you wish to apply the new master layout. Apply New Layout (Important): Right-click any selected slide, point to Layout, and click the slide containing the desired layout from the layout gallery. Delete any unwanted slides or duplicates. To copy the Customized Background from Another Presentation on Mac Click New Slide from the Home tab's Slides group and select Insert Slides from Other Presentation… Navigate to the PowerPoint presentation file that contains the background you wish to copy. Double-click or press Insert. This prompts the Slide Finder dialogue box. Make sure Keep design of original slides is unchecked and click the slide(s) that contains the background you want. Hold Shift key to select multiple slides. Click the left-hand slide preview to which you wish to apply the new master layout. Apply New Layout (Important): Click Layout from the Home tab's Slides group, and click the slide containing the desired layout from the layout gallery. Delete any unwanted slides or duplicates.
  2. This is a Safe Harbor Front slide, one of two Safe Harbor Statement slides included in this template. One of the Safe Harbor slides must be used if your presentation covers material affected by Oracle’s Revenue Recognition Policy To learn more about this policy, e-mail: Revrec-americasiebc_us@oracle.com For internal communication, Safe Harbor Statements are not required. However, there is an applicable disclaimer (Exhibit E) that should be used, found in the Oracle Revenue Recognition Policy for Future Product Communications. Copy and paste this link into a web browser, to find out more information. http://my.oracle.com/site/fin/gfo/GlobalProcesses/cnt452504.pdf For all external communications such as press release, roadmaps, PowerPoint presentations, Safe Harbor Statements are required. You can refer to the link mentioned above to find out additional information/disclaimers required depending on your audience.
  3. We define a Lambda expression as an anonymous function (like a method, but because it is not associated with a class we call it a function). Like methods there are parameters, a body, a return type and even thrown exceptions. What Lambda expressions really brings to Java is a simple way to parameterise behaviour. The sequence of methods we have here defines what we want to do, i.e. filter the stream, map its values and so on, but how this happens is defined by the Lambda expressions we pass as parameters.
  4. Erased function types are the worst of both worlds
  5. Stream is an interface, but in Java SE 8 we can now have static methods in interfaces, hence Stream.of() Files.walk will walk a file tree from a given Path argument Spliterator interface that represents an object for traversing or partitioning elements of a source
  6. This is a Title Slide with Java FY15 Theme slide ideal for including the Java Theme with a brief title, subtitle and presenter information. To customize this slide with your own picture: Right-click the slide area and choose Format Background from the pop-up menu. From the Fill menu, click Picture and texture fill. Under Insert from: click File. Locate your new picture and click Insert. To copy the Customized Background from Another Presentation on PC Click New Slide from the Home tab's Slides group and select Reuse Slides. Click Browse in the Reuse Slides panel and select Browse Files. Double-click the PowerPoint presentation that contains the background you wish to copy. Check Keep Source Formatting and click the slide that contains the background you want. Click the left-hand slide preview to which you wish to apply the new master layout. Apply New Layout (Important): Right-click any selected slide, point to Layout, and click the slide containing the desired layout from the layout gallery. Delete any unwanted slides or duplicates. To copy the Customized Background from Another Presentation on Mac Click New Slide from the Home tab's Slides group and select Insert Slides from Other Presentation… Navigate to the PowerPoint presentation file that contains the background you wish to copy. Double-click or press Insert. This prompts the Slide Finder dialogue box. Make sure Keep design of original slides is unchecked and click the slide(s) that contains the background you want. Hold Shift key to select multiple slides. Click the left-hand slide preview to which you wish to apply the new master layout. Apply New Layout (Important): Click Layout from the Home tab's Slides group, and click the slide containing the desired layout from the layout gallery. Delete any unwanted slides or duplicates.