SlideShare a Scribd company logo
Functional Programming With Lambdas and Streams in JDK8
Simon Ritter
Head of Java Technology Evangelism
Oracle Corporation
Twitter: @speakjava
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.
1996 … 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014
1.0 5.0 6 7 8
java.lang.Thread
java.util.concurrent
(jsr166)
Fork/Join Framework
(jsr166y)
Project LambdaConcurrency in Java
Phasers, etc
(jsr166)
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Lambdas In Java
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
The Problem: External Iteration
List<Student> students = ...
double highestScore = 0.0;
for (Student s : students) {
if (s.getGradYear() == 2011) {
if (s.getScore() > highestScore)
highestScore = s.score;
}
}
• Our code controls iteration
• Inherently serial: iterate from
beginning to end
• Not thread-safe
• Business logic is stateful
• Mutable accumulator variable
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Internal Iteration With Inner Classes
• Iteration handled by the library
• Not inherently serial – traversal may
be done in parallel
• Traversal may be done lazily – so one
pass, rather than three
• Thread safe – client logic is stateless
• High barrier to use
– Syntactically ugly
More Functional
double highestScore = students
.filter(new Predicate<Student>() {
public boolean op(Student s) {
return s.getGradYear() == 2011;
}
})
.map(new Mapper<Student,Double>() {
public Double extract(Student s) {
return s.getScore();
}
})
.max();
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Internal Iteration With Lambdas
List<Student> students = ...
double highestScore = students
.filter(Student s -> s.getGradYear() == 2011)
.map(Student s -> s.getScore())
.max();
• More readable
• More abstract
• Less error-prone
NOTE: This is not JDK8 code
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
enclosing 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 For Lambdas?
• ‘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.
Method References
• Method references let us reuse a method as a lambda expression
FileFilter x = File f -> f.canRead();
FileFilter x = File::canRead;
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Constructor References
• Same concept as a method reference
– For the constructor
Factory<List<String>> f = ArrayList<String>::new;
Factory<List<String>> f = () -> return new ArrayList<String>();
Replace with
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Library Evolution
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Library Evolution Goal
• Requirement: aggregate operations on collections
–New methods required on Collections to facilitate this
• This is problematic
– Can’t add new methods to interfaces without modifying all implementations
– Can’t necessarily find or control all implementations
int heaviestBlueBlock = blocks
.filter(b -> b.getColor() == BLUE)
.map(Block::getWeight)
.reduce(0, Integer::max);
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Solution: Default Methods
• Specified in the interface
• From the caller’s perspective, just an ordinary interface method
• Provides a default implementation
• Default only used when implementation classes do not provide a body for the
extension method
• Implementation classes can provide a better version, or not
interface Collection<E> {
default Stream<E> stream() {
return StreamSupport.stream(spliterator());
}
}
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Virtual Extension Methods
• Err, isn’t this implementing multiple inheritance for Java?
• Yes, but Java already has multiple inheritance of types
• This adds multiple inheritance of behavior too
• But not state, which is where most of the trouble is
• Can still be a source of complexity
• Class implements two interfaces, both of which have default methods
• Same signature
• How does the compiler differentiate?
• Static methods also allowed in interfaces in Java SE 8
Stop right there!
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Functional Interface Definition
• Single Abstract Method (SAM) type
• A functional interface is an interface that has one abstract method
– Represents a single function contract
– Doesn’t mean it only has one method
• @FunctionalInterface annotation
– Helps ensure the functional interface contract is honoured
– Compiler error if not a SAM
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Lambdas In Full Flow:
Streams
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Stream Overview
• Abstraction for specifying aggregate computations
– Not a data structure
– Can be infinite
• Simplifies the description of aggregate computations
– Exposes opportunities for optimisation
– Fusing, laziness and parallelism
At The High Level
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.
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 © 2014, Oracle and/or its affiliates. All rights reserved.
Maps and FlatMaps
Map Values in a Stream
Map
FlatMap
Input Stream
Input Stream
1-to-1 mapping
1-to-many mapping
Output Stream
Output Stream
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
Helping To Eliminate the NullPointerException
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Example 1
Convert words in list to upper case
List<String> output = wordList
.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Example 1
Convert words in list to upper case (in parallel)
List<String> output = wordList
.parallelStream()
.map(String::toUpperCase)
.collect(Collectors.toList());
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Example 2
• BufferedReader has new method
– Stream<String> lines()
Count lines in a file
long count = bufferedReader
.lines()
.count();
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Example 3
Join lines 3-4 into a single string
String output = bufferedReader
.lines()
.skip(2)
.limit(2)
.collect(Collectors.joining());
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Example 4
Collect all words in a file into a list
List<String> output = reader
.lines()
.flatMap(line -> Stream.of(line.split(REGEXP)))
.filter(word -> word.length() > 0)
.collect(Collectors.toList());
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Example 5
List of unique words in lowercase, sorted by length
List<String> output = reader
.lines()
.flatMap(line -> Stream.of(line.split(REGEXP)))
.filter(word -> word.length() > 0)
.map(String::toLowerCase)
.distinct()
.sorted((x, y) -> x.length() - y.length())
.collect(Collectors.toList());
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Example 6: Real World
Infinite stream from thermal sensor
private int double currentTemperature;
...
thermalReader
.lines()
.mapToDouble(s ->
Double.parseDouble(s.substring(0, s.length() - 1)))
.map(t -> ((t – 32) * 5 / 9)
.filter(t -> t != currentTemperature)
.peek(t -> listener.ifPresent(l -> l.temperatureChanged(t)))
.forEach(t -> currentTemperature = t);
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Example 6: Real World
Infinite stream from thermal sensor
private int double currentTemperature;
...
thermalReader
.lines()
.mapToDouble(s ->
Double.parseDouble(s.substring(0, s.length() - )))
.map(t -> ((t – 32) * 5 / 9)
.filter(t -> t != this.currentTemperature)
.peek(t -> listener.ifPresent(l -> l.temperatureChanged(t)))
.forEach(t -> this.currentTemperature = t);
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Conclusions
• Java needs lambda statements
– Significant improvements in existing libraries are required
• Require a mechanism for interface evolution
– Solution: virtual extension methods
• Bulk operations on Collections
– Much simpler with Lambdas
• Java SE 8 evolves the language, libraries, and VM together
Simon Ritter
Oracle Corporartion
Twitter: @speakjava
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Ad

More Related Content

What's hot (17)

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
Simon Ritter
 
Project Jigsaw in JDK9
Project Jigsaw in JDK9Project Jigsaw in JDK9
Project Jigsaw in JDK9
Simon 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
 
Java 8 Features
Java 8 FeaturesJava 8 Features
Java 8 Features
Leninkumar Koppoju
 
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
New York City College of Technology Computer Systems Technology Colloquium
 
Lambdas & Streams
Lambdas & StreamsLambdas & Streams
Lambdas & Streams
C4Media
 
JDK8 Streams
JDK8 StreamsJDK8 Streams
JDK8 Streams
Bansilal Haudakari
 
The Java Carputer
The Java CarputerThe Java Carputer
The Java Carputer
Simon Ritter
 
Java SE 8 library design
Java SE 8 library designJava SE 8 library design
Java SE 8 library design
Stephen Colebourne
 
Java SE 8 - New Features
Java SE 8 - New FeaturesJava SE 8 - New Features
Java SE 8 - New Features
Naveen Hegde
 
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
Emiel Paasschens
 
Java 8
Java 8Java 8
Java 8
Sudipta K Paik
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features Overview
Sergii Stets
 
The Road to Lambda - Mike Duigou
The Road to Lambda - Mike DuigouThe Road to Lambda - Mike Duigou
The Road to Lambda - Mike Duigou
jaxconf
 
Chap2java5th
Chap2java5thChap2java5th
Chap2java5th
Asfand Hassan
 
java 8 new features
java 8 new features java 8 new features
java 8 new features
Rohit Verma
 
Major Java 8 features
Major Java 8 featuresMajor Java 8 features
Major Java 8 features
Sanjoy Kumar Roy
 

Similar to Functional Programming With Lambdas and Streams in JDK8 (20)

Lambdas And Streams in JDK8
Lambdas And Streams in JDK8Lambdas And Streams in JDK8
Lambdas And Streams in JDK8
Simon Ritter
 
What's New in Java 8
What's New in Java 8What's New in Java 8
What's New in Java 8
javafxpert
 
Lambdas Hands On Lab
Lambdas Hands On LabLambdas Hands On Lab
Lambdas Hands On Lab
Simon Ritter
 
Lambdas And Streams Hands On Lab, JavaOne 2014
Lambdas And Streams Hands On Lab, JavaOne 2014Lambdas And Streams Hands On Lab, JavaOne 2014
Lambdas And Streams Hands On Lab, JavaOne 2014
Simon Ritter
 
Silicon Valley JUG meetup July 18, 2018
Silicon Valley JUG meetup July 18, 2018Silicon Valley JUG meetup July 18, 2018
Silicon Valley JUG meetup July 18, 2018
Oracle Developers
 
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
JavaDayUA
 
Java 8 Interview Questions and Answers PDF By ScholarHat.pdf
Java 8 Interview Questions and Answers PDF By ScholarHat.pdfJava 8 Interview Questions and Answers PDF By ScholarHat.pdf
Java 8 Interview Questions and Answers PDF By ScholarHat.pdf
Scholarhat
 
Java 8 Overview
Java 8 OverviewJava 8 Overview
Java 8 Overview
Nicola Pedot
 
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
JavaDayUA
 
Lambdas And Streams Hands On Lab
Lambdas And Streams Hands On LabLambdas And Streams Hands On Lab
Lambdas And Streams Hands On Lab
Simon Ritter
 
Completable future
Completable futureCompletable future
Completable future
Srinivasan Raghvan
 
Reactive Java Programming: A new Asynchronous Database Access API by Kuassi M...
Reactive Java Programming: A new Asynchronous Database Access API by Kuassi M...Reactive Java Programming: A new Asynchronous Database Access API by Kuassi M...
Reactive Java Programming: A new Asynchronous Database Access API by Kuassi M...
Oracle Developers
 
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
Harmeet Singh(Taara)
 
Colloquium Report
Colloquium ReportColloquium Report
Colloquium Report
Mohammad Faizan
 
ADBA (Asynchronous Database Access)
ADBA (Asynchronous Database Access)ADBA (Asynchronous Database Access)
ADBA (Asynchronous Database Access)
Logico
 
Lambdas in Java 8
Lambdas in Java 8Lambdas in Java 8
Lambdas in Java 8
Tobias Coetzee
 
Keynote (Nandini Ramani) - The Role of Java in Heterogeneous Computing & How ...
Keynote (Nandini Ramani) - The Role of Java in Heterogeneous Computing & How ...Keynote (Nandini Ramani) - The Role of Java in Heterogeneous Computing & How ...
Keynote (Nandini Ramani) - The Role of Java in Heterogeneous Computing & How ...
AMD Developer Central
 
What`s New in Java 8
What`s New in Java 8What`s New in Java 8
What`s New in Java 8
Mohsen Zainalpour
 
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
Edward Burns
 
NUS Hackers Club Mar 21 - Whats New in JavaSE 8?
NUS Hackers Club Mar 21 - Whats New in JavaSE 8?NUS Hackers Club Mar 21 - Whats New in JavaSE 8?
NUS Hackers Club Mar 21 - Whats New in JavaSE 8?
Chuk-Munn Lee
 
Lambdas And Streams in JDK8
Lambdas And Streams in JDK8Lambdas And Streams in JDK8
Lambdas And Streams in JDK8
Simon Ritter
 
What's New in Java 8
What's New in Java 8What's New in Java 8
What's New in Java 8
javafxpert
 
Lambdas Hands On Lab
Lambdas Hands On LabLambdas Hands On Lab
Lambdas Hands On Lab
Simon Ritter
 
Lambdas And Streams Hands On Lab, JavaOne 2014
Lambdas And Streams Hands On Lab, JavaOne 2014Lambdas And Streams Hands On Lab, JavaOne 2014
Lambdas And Streams Hands On Lab, JavaOne 2014
Simon Ritter
 
Silicon Valley JUG meetup July 18, 2018
Silicon Valley JUG meetup July 18, 2018Silicon Valley JUG meetup July 18, 2018
Silicon Valley JUG meetup July 18, 2018
Oracle Developers
 
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
JavaDayUA
 
Java 8 Interview Questions and Answers PDF By ScholarHat.pdf
Java 8 Interview Questions and Answers PDF By ScholarHat.pdfJava 8 Interview Questions and Answers PDF By ScholarHat.pdf
Java 8 Interview Questions and Answers PDF By ScholarHat.pdf
Scholarhat
 
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
JavaDayUA
 
Lambdas And Streams Hands On Lab
Lambdas And Streams Hands On LabLambdas And Streams Hands On Lab
Lambdas And Streams Hands On Lab
Simon Ritter
 
Reactive Java Programming: A new Asynchronous Database Access API by Kuassi M...
Reactive Java Programming: A new Asynchronous Database Access API by Kuassi M...Reactive Java Programming: A new Asynchronous Database Access API by Kuassi M...
Reactive Java Programming: A new Asynchronous Database Access API by Kuassi M...
Oracle Developers
 
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
Harmeet Singh(Taara)
 
ADBA (Asynchronous Database Access)
ADBA (Asynchronous Database Access)ADBA (Asynchronous Database Access)
ADBA (Asynchronous Database Access)
Logico
 
Keynote (Nandini Ramani) - The Role of Java in Heterogeneous Computing & How ...
Keynote (Nandini Ramani) - The Role of Java in Heterogeneous Computing & How ...Keynote (Nandini Ramani) - The Role of Java in Heterogeneous Computing & How ...
Keynote (Nandini Ramani) - The Role of Java in Heterogeneous Computing & How ...
AMD Developer Central
 
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
Edward Burns
 
NUS Hackers Club Mar 21 - Whats New in JavaSE 8?
NUS Hackers Club Mar 21 - Whats New in JavaSE 8?NUS Hackers Club Mar 21 - Whats New in JavaSE 8?
NUS Hackers Club Mar 21 - Whats New in JavaSE 8?
Chuk-Munn Lee
 
Ad

More from IndicThreads (20)

Http2 is here! And why the web needs it
Http2 is here! And why the web needs itHttp2 is here! And why the web needs it
Http2 is here! And why the web needs it
IndicThreads
 
Understanding Bitcoin (Blockchain) and its Potential for Disruptive Applications
Understanding Bitcoin (Blockchain) and its Potential for Disruptive ApplicationsUnderstanding Bitcoin (Blockchain) and its Potential for Disruptive Applications
Understanding Bitcoin (Blockchain) and its Potential for Disruptive Applications
IndicThreads
 
Go Programming Language - Learning The Go Lang way
Go Programming Language - Learning The Go Lang wayGo Programming Language - Learning The Go Lang way
Go Programming Language - Learning The Go Lang way
IndicThreads
 
Building Resilient Microservices
Building Resilient Microservices Building Resilient Microservices
Building Resilient Microservices
IndicThreads
 
App using golang indicthreads
App using golang  indicthreadsApp using golang  indicthreads
App using golang indicthreads
IndicThreads
 
Building on quicksand microservices indicthreads
Building on quicksand microservices  indicthreadsBuilding on quicksand microservices  indicthreads
Building on quicksand microservices indicthreads
IndicThreads
 
How to Think in RxJava Before Reacting
How to Think in RxJava Before ReactingHow to Think in RxJava Before Reacting
How to Think in RxJava Before Reacting
IndicThreads
 
Iot secure connected devices indicthreads
Iot secure connected devices indicthreadsIot secure connected devices indicthreads
Iot secure connected devices indicthreads
IndicThreads
 
Real world IoT for enterprises
Real world IoT for enterprisesReal world IoT for enterprises
Real world IoT for enterprises
IndicThreads
 
IoT testing and quality assurance indicthreads
IoT testing and quality assurance indicthreadsIoT testing and quality assurance indicthreads
IoT testing and quality assurance indicthreads
IndicThreads
 
Functional Programming Past Present Future
Functional Programming Past Present FutureFunctional Programming Past Present Future
Functional Programming Past Present Future
IndicThreads
 
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
 
Building & scaling a live streaming mobile platform - Gr8 road to fame
Building & scaling a live streaming mobile platform - Gr8 road to fameBuilding & scaling a live streaming mobile platform - Gr8 road to fame
Building & scaling a live streaming mobile platform - Gr8 road to fame
IndicThreads
 
Internet of things architecture perspective - IndicThreads Conference
Internet of things architecture perspective - IndicThreads ConferenceInternet of things architecture perspective - IndicThreads Conference
Internet of things architecture perspective - IndicThreads Conference
IndicThreads
 
Cars and Computers: Building a Java Carputer
 Cars and Computers: Building a Java Carputer Cars and Computers: Building a Java Carputer
Cars and Computers: Building a Java Carputer
IndicThreads
 
Scrap Your MapReduce - Apache Spark
 Scrap Your MapReduce - Apache Spark Scrap Your MapReduce - Apache Spark
Scrap Your MapReduce - Apache Spark
IndicThreads
 
Continuous Integration (CI) and Continuous Delivery (CD) using Jenkins & Docker
 Continuous Integration (CI) and Continuous Delivery (CD) using Jenkins & Docker Continuous Integration (CI) and Continuous Delivery (CD) using Jenkins & Docker
Continuous Integration (CI) and Continuous Delivery (CD) using Jenkins & Docker
IndicThreads
 
Speed up your build pipeline for faster feedback
Speed up your build pipeline for faster feedbackSpeed up your build pipeline for faster feedback
Speed up your build pipeline for faster feedback
IndicThreads
 
Unraveling OpenStack Clouds
 Unraveling OpenStack Clouds Unraveling OpenStack Clouds
Unraveling OpenStack Clouds
IndicThreads
 
Digital Transformation of the Enterprise. What IT leaders need to know!
Digital Transformation of the Enterprise. What IT  leaders need to know!Digital Transformation of the Enterprise. What IT  leaders need to know!
Digital Transformation of the Enterprise. What IT leaders need to know!
IndicThreads
 
Http2 is here! And why the web needs it
Http2 is here! And why the web needs itHttp2 is here! And why the web needs it
Http2 is here! And why the web needs it
IndicThreads
 
Understanding Bitcoin (Blockchain) and its Potential for Disruptive Applications
Understanding Bitcoin (Blockchain) and its Potential for Disruptive ApplicationsUnderstanding Bitcoin (Blockchain) and its Potential for Disruptive Applications
Understanding Bitcoin (Blockchain) and its Potential for Disruptive Applications
IndicThreads
 
Go Programming Language - Learning The Go Lang way
Go Programming Language - Learning The Go Lang wayGo Programming Language - Learning The Go Lang way
Go Programming Language - Learning The Go Lang way
IndicThreads
 
Building Resilient Microservices
Building Resilient Microservices Building Resilient Microservices
Building Resilient Microservices
IndicThreads
 
App using golang indicthreads
App using golang  indicthreadsApp using golang  indicthreads
App using golang indicthreads
IndicThreads
 
Building on quicksand microservices indicthreads
Building on quicksand microservices  indicthreadsBuilding on quicksand microservices  indicthreads
Building on quicksand microservices indicthreads
IndicThreads
 
How to Think in RxJava Before Reacting
How to Think in RxJava Before ReactingHow to Think in RxJava Before Reacting
How to Think in RxJava Before Reacting
IndicThreads
 
Iot secure connected devices indicthreads
Iot secure connected devices indicthreadsIot secure connected devices indicthreads
Iot secure connected devices indicthreads
IndicThreads
 
Real world IoT for enterprises
Real world IoT for enterprisesReal world IoT for enterprises
Real world IoT for enterprises
IndicThreads
 
IoT testing and quality assurance indicthreads
IoT testing and quality assurance indicthreadsIoT testing and quality assurance indicthreads
IoT testing and quality assurance indicthreads
IndicThreads
 
Functional Programming Past Present Future
Functional Programming Past Present FutureFunctional Programming Past Present Future
Functional Programming Past Present Future
IndicThreads
 
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
 
Building & scaling a live streaming mobile platform - Gr8 road to fame
Building & scaling a live streaming mobile platform - Gr8 road to fameBuilding & scaling a live streaming mobile platform - Gr8 road to fame
Building & scaling a live streaming mobile platform - Gr8 road to fame
IndicThreads
 
Internet of things architecture perspective - IndicThreads Conference
Internet of things architecture perspective - IndicThreads ConferenceInternet of things architecture perspective - IndicThreads Conference
Internet of things architecture perspective - IndicThreads Conference
IndicThreads
 
Cars and Computers: Building a Java Carputer
 Cars and Computers: Building a Java Carputer Cars and Computers: Building a Java Carputer
Cars and Computers: Building a Java Carputer
IndicThreads
 
Scrap Your MapReduce - Apache Spark
 Scrap Your MapReduce - Apache Spark Scrap Your MapReduce - Apache Spark
Scrap Your MapReduce - Apache Spark
IndicThreads
 
Continuous Integration (CI) and Continuous Delivery (CD) using Jenkins & Docker
 Continuous Integration (CI) and Continuous Delivery (CD) using Jenkins & Docker Continuous Integration (CI) and Continuous Delivery (CD) using Jenkins & Docker
Continuous Integration (CI) and Continuous Delivery (CD) using Jenkins & Docker
IndicThreads
 
Speed up your build pipeline for faster feedback
Speed up your build pipeline for faster feedbackSpeed up your build pipeline for faster feedback
Speed up your build pipeline for faster feedback
IndicThreads
 
Unraveling OpenStack Clouds
 Unraveling OpenStack Clouds Unraveling OpenStack Clouds
Unraveling OpenStack Clouds
IndicThreads
 
Digital Transformation of the Enterprise. What IT leaders need to know!
Digital Transformation of the Enterprise. What IT  leaders need to know!Digital Transformation of the Enterprise. What IT  leaders need to know!
Digital Transformation of the Enterprise. What IT leaders need to know!
IndicThreads
 
Ad

Recently uploaded (20)

Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AIScaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
danshalev
 
Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)
Allon Mureinik
 
Adobe Master Collection CC Crack Advance Version 2025
Adobe Master Collection CC Crack Advance Version 2025Adobe Master Collection CC Crack Advance Version 2025
Adobe Master Collection CC Crack Advance Version 2025
kashifyounis067
 
EASEUS Partition Master Crack + License Code
EASEUS Partition Master Crack + License CodeEASEUS Partition Master Crack + License Code
EASEUS Partition Master Crack + License Code
aneelaramzan63
 
Download Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With LatestDownload Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With Latest
tahirabibi60507
 
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Andre Hora
 
Maxon CINEMA 4D 2025 Crack FREE Download LINK
Maxon CINEMA 4D 2025 Crack FREE Download LINKMaxon CINEMA 4D 2025 Crack FREE Download LINK
Maxon CINEMA 4D 2025 Crack FREE Download LINK
younisnoman75
 
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and CollaborateMeet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Maxim Salnikov
 
Pixologic ZBrush Crack Plus Activation Key [Latest 2025] New Version
Pixologic ZBrush Crack Plus Activation Key [Latest 2025] New VersionPixologic ZBrush Crack Plus Activation Key [Latest 2025] New Version
Pixologic ZBrush Crack Plus Activation Key [Latest 2025] New Version
saimabibi60507
 
Explaining GitHub Actions Failures with Large Language Models Challenges, In...
Explaining GitHub Actions Failures with Large Language Models Challenges, In...Explaining GitHub Actions Failures with Large Language Models Challenges, In...
Explaining GitHub Actions Failures with Large Language Models Challenges, In...
ssuserb14185
 
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRYLEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
NidaFarooq10
 
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Dele Amefo
 
FL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full VersionFL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full Version
tahirabibi60507
 
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Ranjan Baisak
 
Expand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchangeExpand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchange
Fexle Services Pvt. Ltd.
 
Douwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License codeDouwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License code
aneelaramzan63
 
Automation Techniques in RPA - UiPath Certificate
Automation Techniques in RPA - UiPath CertificateAutomation Techniques in RPA - UiPath Certificate
Automation Techniques in RPA - UiPath Certificate
VICTOR MAESTRE RAMIREZ
 
Exploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the FutureExploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the Future
ICS
 
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
steaveroggers
 
Revolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptxRevolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptx
nidhisingh691197
 
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AIScaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
danshalev
 
Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)
Allon Mureinik
 
Adobe Master Collection CC Crack Advance Version 2025
Adobe Master Collection CC Crack Advance Version 2025Adobe Master Collection CC Crack Advance Version 2025
Adobe Master Collection CC Crack Advance Version 2025
kashifyounis067
 
EASEUS Partition Master Crack + License Code
EASEUS Partition Master Crack + License CodeEASEUS Partition Master Crack + License Code
EASEUS Partition Master Crack + License Code
aneelaramzan63
 
Download Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With LatestDownload Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With Latest
tahirabibi60507
 
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Andre Hora
 
Maxon CINEMA 4D 2025 Crack FREE Download LINK
Maxon CINEMA 4D 2025 Crack FREE Download LINKMaxon CINEMA 4D 2025 Crack FREE Download LINK
Maxon CINEMA 4D 2025 Crack FREE Download LINK
younisnoman75
 
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and CollaborateMeet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Maxim Salnikov
 
Pixologic ZBrush Crack Plus Activation Key [Latest 2025] New Version
Pixologic ZBrush Crack Plus Activation Key [Latest 2025] New VersionPixologic ZBrush Crack Plus Activation Key [Latest 2025] New Version
Pixologic ZBrush Crack Plus Activation Key [Latest 2025] New Version
saimabibi60507
 
Explaining GitHub Actions Failures with Large Language Models Challenges, In...
Explaining GitHub Actions Failures with Large Language Models Challenges, In...Explaining GitHub Actions Failures with Large Language Models Challenges, In...
Explaining GitHub Actions Failures with Large Language Models Challenges, In...
ssuserb14185
 
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRYLEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
NidaFarooq10
 
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Dele Amefo
 
FL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full VersionFL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full Version
tahirabibi60507
 
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Ranjan Baisak
 
Expand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchangeExpand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchange
Fexle Services Pvt. Ltd.
 
Douwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License codeDouwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License code
aneelaramzan63
 
Automation Techniques in RPA - UiPath Certificate
Automation Techniques in RPA - UiPath CertificateAutomation Techniques in RPA - UiPath Certificate
Automation Techniques in RPA - UiPath Certificate
VICTOR MAESTRE RAMIREZ
 
Exploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the FutureExploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the Future
ICS
 
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
steaveroggers
 
Revolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptxRevolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptx
nidhisingh691197
 

Functional Programming With Lambdas and Streams in JDK8

  • 1. Functional Programming With Lambdas and Streams in JDK8 Simon Ritter Head of Java Technology Evangelism Oracle Corporation Twitter: @speakjava
  • 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. 1996 … 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 1.0 5.0 6 7 8 java.lang.Thread java.util.concurrent (jsr166) Fork/Join Framework (jsr166y) Project LambdaConcurrency in Java Phasers, etc (jsr166)
  • 4. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Lambdas In Java
  • 5. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. The Problem: External Iteration List<Student> students = ... double highestScore = 0.0; for (Student s : students) { if (s.getGradYear() == 2011) { if (s.getScore() > highestScore) highestScore = s.score; } } • Our code controls iteration • Inherently serial: iterate from beginning to end • Not thread-safe • Business logic is stateful • Mutable accumulator variable
  • 6. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Internal Iteration With Inner Classes • Iteration handled by the library • Not inherently serial – traversal may be done in parallel • Traversal may be done lazily – so one pass, rather than three • Thread safe – client logic is stateless • High barrier to use – Syntactically ugly More Functional double highestScore = students .filter(new Predicate<Student>() { public boolean op(Student s) { return s.getGradYear() == 2011; } }) .map(new Mapper<Student,Double>() { public Double extract(Student s) { return s.getScore(); } }) .max();
  • 7. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Internal Iteration With Lambdas List<Student> students = ... double highestScore = students .filter(Student s -> s.getGradYear() == 2011) .map(Student s -> s.getScore()) .max(); • More readable • More abstract • Less error-prone NOTE: This is not JDK8 code
  • 8. 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
  • 9. 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(); }
  • 10. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Local Variable Capture • Lambda expressions can refer to effectively final local variables from the enclosing 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); }
  • 11. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. What Does ‘this’ Mean For Lambdas? • ‘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
  • 12. 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++)); } }
  • 13. 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
  • 14. 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);
  • 15. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Method References • Method references let us reuse a method as a lambda expression FileFilter x = File f -> f.canRead(); FileFilter x = File::canRead;
  • 16. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Constructor References • Same concept as a method reference – For the constructor Factory<List<String>> f = ArrayList<String>::new; Factory<List<String>> f = () -> return new ArrayList<String>(); Replace with
  • 17. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Library Evolution
  • 18. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Library Evolution Goal • Requirement: aggregate operations on collections –New methods required on Collections to facilitate this • This is problematic – Can’t add new methods to interfaces without modifying all implementations – Can’t necessarily find or control all implementations int heaviestBlueBlock = blocks .filter(b -> b.getColor() == BLUE) .map(Block::getWeight) .reduce(0, Integer::max);
  • 19. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Solution: Default Methods • Specified in the interface • From the caller’s perspective, just an ordinary interface method • Provides a default implementation • Default only used when implementation classes do not provide a body for the extension method • Implementation classes can provide a better version, or not interface Collection<E> { default Stream<E> stream() { return StreamSupport.stream(spliterator()); } }
  • 20. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Virtual Extension Methods • Err, isn’t this implementing multiple inheritance for Java? • Yes, but Java already has multiple inheritance of types • This adds multiple inheritance of behavior too • But not state, which is where most of the trouble is • Can still be a source of complexity • Class implements two interfaces, both of which have default methods • Same signature • How does the compiler differentiate? • Static methods also allowed in interfaces in Java SE 8 Stop right there!
  • 21. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Functional Interface Definition • Single Abstract Method (SAM) type • A functional interface is an interface that has one abstract method – Represents a single function contract – Doesn’t mean it only has one method • @FunctionalInterface annotation – Helps ensure the functional interface contract is honoured – Compiler error if not a SAM
  • 22. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Lambdas In Full Flow: Streams
  • 23. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Stream Overview • Abstraction for specifying aggregate computations – Not a data structure – Can be infinite • Simplifies the description of aggregate computations – Exposes opportunities for optimisation – Fusing, laziness and parallelism At The High Level
  • 24. 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
  • 25. 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
  • 26. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 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
  • 27. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Maps and FlatMaps Map Values in a Stream Map FlatMap Input Stream Input Stream 1-to-1 mapping 1-to-many mapping Output Stream Output Stream
  • 28. 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 Helping To Eliminate the NullPointerException
  • 29. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Example 1 Convert words in list to upper case List<String> output = wordList .stream() .map(String::toUpperCase) .collect(Collectors.toList());
  • 30. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Example 1 Convert words in list to upper case (in parallel) List<String> output = wordList .parallelStream() .map(String::toUpperCase) .collect(Collectors.toList());
  • 31. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Example 2 • BufferedReader has new method – Stream<String> lines() Count lines in a file long count = bufferedReader .lines() .count();
  • 32. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Example 3 Join lines 3-4 into a single string String output = bufferedReader .lines() .skip(2) .limit(2) .collect(Collectors.joining());
  • 33. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Example 4 Collect all words in a file into a list List<String> output = reader .lines() .flatMap(line -> Stream.of(line.split(REGEXP))) .filter(word -> word.length() > 0) .collect(Collectors.toList());
  • 34. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Example 5 List of unique words in lowercase, sorted by length List<String> output = reader .lines() .flatMap(line -> Stream.of(line.split(REGEXP))) .filter(word -> word.length() > 0) .map(String::toLowerCase) .distinct() .sorted((x, y) -> x.length() - y.length()) .collect(Collectors.toList());
  • 35. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Example 6: Real World Infinite stream from thermal sensor private int double currentTemperature; ... thermalReader .lines() .mapToDouble(s -> Double.parseDouble(s.substring(0, s.length() - 1))) .map(t -> ((t – 32) * 5 / 9) .filter(t -> t != currentTemperature) .peek(t -> listener.ifPresent(l -> l.temperatureChanged(t))) .forEach(t -> currentTemperature = t);
  • 36. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Example 6: Real World Infinite stream from thermal sensor private int double currentTemperature; ... thermalReader .lines() .mapToDouble(s -> Double.parseDouble(s.substring(0, s.length() - ))) .map(t -> ((t – 32) * 5 / 9) .filter(t -> t != this.currentTemperature) .peek(t -> listener.ifPresent(l -> l.temperatureChanged(t))) .forEach(t -> this.currentTemperature = t);
  • 37. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Conclusions • Java needs lambda statements – Significant improvements in existing libraries are required • Require a mechanism for interface evolution – Solution: virtual extension methods • Bulk operations on Collections – Much simpler with Lambdas • Java SE 8 evolves the language, libraries, and VM together
  • 38. Simon Ritter Oracle Corporartion Twitter: @speakjava Copyright © 2014, Oracle and/or its affiliates. All rights reserved.