SlideShare a Scribd company logo
1 of 38
Platinum Sponsor
RETHINKING YOUR CODE WITH
LAMBDAS & STREAMS IN JAVA SE 8
Simon Ritter, Oracle
@speakjava
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.2
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.
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.3
2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014
1.4 5.0 6 7 8
java.lang.Thread
java.util.concurrent
(jsr166)
Fork/Join Framework
(jsr166y)
Project LambdaConcurrency in Java
Phasers, etc
(jsr166)
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.4
Lambdas In Java
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.5
The Problem: External Iteration
List<Student> students = ...
double highestScore = 0.0;
for (Student s : students) {
if (s.gradYear == 2011) {
if (s.score > highestScore) {
highestScore = s.score;
}
}
}
• Our code controls iteration
• Inherently serial: iterate from
beginning to end
• Not thread-safe because
business logic is stateful
(mutable accumulator
variable)
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.6
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, Fluent
List<Student> students = ...
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 © 2012, Oracle and/or its affiliates. All rights reserved.7
Internal Iteration With Lambdas
SomeList<Student> students = ...
double highestScore = students.
filter(Student s -> s.getGradYear() == 2011).
map(Student s -> s.getScore()).
max();
• More readable
• More abstract
• Less error-prone
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.8
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 © 2012, Oracle and/or its affiliates. All rights reserved.9
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 © 2012, Oracle and/or its affiliates. All rights reserved.10
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 fina
void expire(File root, long before) {
root.listFiles(File p -> p.lastModified() <= before);
}
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.11
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
class SessionManager {
long before = ...;
void expire(File root) {
// refers to ‘this.before’, just like outside the lambda
root.listFiles(File p -> checkExpiry(p.lastModified(), this.before));
}
boolean checkExpiry(long time, long expiry) { ... }
}
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.12
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 © 2012, Oracle and/or its affiliates. All rights reserved.13
Method References
• Method references let us reuse a method as a lambda expression
FileFilter x = File f -> f.canRead();
FileFilter x = File::canRead;
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.14
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>();
Equivalent to
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.15
Library Evolution
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.16
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 © 2012, Oracle and/or its affiliates. All rights reserved.17
Solution: Extension 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
AKA Defender or Default Methods
interface Collection<E> {
default Stream<E> stream() {
return StreamSupport.stream(spliterator());
}
}
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.18
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 © 2012, Oracle and/or its affiliates. All rights reserved.19
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
 Interfaces can now have static methods
 @FunctionalInterface annotation
– Helps ensure the functional interface contract is honoured
– Compiler error if not a SAM
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.20
Lambdas In Full Flow:
Streams
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.21
Aggregate Operations
 Most business logic is about aggregate operations
– “Most profitable product by region”
– “Group transactions by currency”
 As we have seen, up to now, Java uses external iteration
– Inherently serial
– Frustratingly imperative
 Java SE 8’s answer: The Stream API
– With help from Lambdas
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.22
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 © 2012, Oracle and/or its affiliates. All rights reserved.23
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 sum = transactions.stream().
filter(t -> t.getBuyer().getCity().equals(“London”)).
mapToInt(Transaction::getPrice).
sum();
Source
Intermediate operation
Terminal operation
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.24
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 © 2012, Oracle and/or its affiliates. All rights reserved.25
Stream Sources Provide
 Access to stream elements
 Decomposition (for parallel operations)
– Fork-join framework
 Stream characteristics
– ORDERED
– DISTINCT
– SORTED
– SIZED
– NONNULL
– IMMUTABLE
– CONCURRENT
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.26
Stream Terminal Operations
 Invoking a terminal operation executes the pipeline
– All operations can execute sequentially or in parallel
 Terminal operations can take advantage of pipeline characteristics
– toArray() can avoid copying for SIZED pipelines by allocating in
advance
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.27
map and flatMap
Map Values in a Stream
 map (one to one)
– Each element of the input stream is mapped to an element in the output
stream
 flatMap (one to many)
– Each element of the input stream is mapped to a new stream
– Streams from all elements are concatenated to form one output stream
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.28
Optional<T>
Reducing NullPointerException Occurrences
String direction = gpsData.getPosition().getLatitude().getDirection();
String direction = “UNKNOWN”;
if (gpsData != null) {
Position p = gpsData.getPosition();
if (p != null) {
Latitude latitude = p.getLatitude();
if (latitude != null)
direction = latitude.getDirection();
}
}
String direction = gpsData.getPosition().getLatitude().getDirection();
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.29
Optional<T>
 Indicates that reference may, or may not have a value
– Makes developer responsible for checking
– A bit like a stream that can only have zero or one elements
Reducing NullPointerException Occurrences
Optional<GPSData> maybeGPS = Optional.ofNullable(gpsData);
maybeGPS.ifPresent(GPSData::printPosition);
GPSData gps = maybeGPS.orElse(new GPSData());
maybeGPS.filter(g -> g.lastRead() < 2).ifPresent(GPSData.display());
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.30
Example 1
Convert words in list to upper case
List<String> output = wordList.
stream().
map(String::toUpperCase).
collect(Collectors.toList());
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.31
Example 1
Convert words in list to upper case (in parallel)
List<String> output = wordList.
parallelStream().
map(String::toUpperCase).
collect(Collectors.toList());
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.32
Example 2
Find words in list with even length
List<String> output = wordList.
parallelStream().
filter(w -> (w.length() & 1 == 0).
collect(Collectors.toList());
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.33
Example 3
 BufferedReader has new method
– Stream<String> lines()
Count lines in a file
long count = bufferedReader.
lines().
count();
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.34
Example 4
Join lines 3-4 into a single string
String output = bufferedReader.
lines().
skip(2).
limit(2).
collect(Collectors.joining());
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.35
Example 6
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 © 2012, Oracle and/or its affiliates. All rights reserved.36
Example 7
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 © 2012, Oracle and/or its affiliates. All rights reserved.37
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
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.38
Graphic Section Divider

More Related Content

What's hot (19)

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
 
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
 
Functional programming with_jdk8-s_ritter
Functional programming with_jdk8-s_ritterFunctional programming with_jdk8-s_ritter
Functional programming with_jdk8-s_ritter
 
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 SE 8 - New Features
Java SE 8 - New FeaturesJava SE 8 - New Features
Java SE 8 - New Features
 
JDK8 Streams
JDK8 StreamsJDK8 Streams
JDK8 Streams
 
Java 8 Features
Java 8 FeaturesJava 8 Features
Java 8 Features
 
Lambdas & Streams
Lambdas & StreamsLambdas & Streams
Lambdas & Streams
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
 
Java 8
Java 8Java 8
Java 8
 
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
 
Streams in Java 8
Streams in Java 8Streams in Java 8
Streams in Java 8
 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8
 
Java 8 Lambda and Streams
Java 8 Lambda and StreamsJava 8 Lambda and Streams
Java 8 Lambda and Streams
 
java 8 new features
java 8 new features java 8 new features
java 8 new features
 
Java 8 streams
Java 8 streamsJava 8 streams
Java 8 streams
 
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
 

Similar to Lambdas and-streams-s ritter-v3

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
 
Lambdas And Streams in JDK8
Lambdas And Streams in JDK8Lambdas And Streams in JDK8
Lambdas And Streams in JDK8Simon Ritter
 
Improved Developer Productivity In JDK8
Improved Developer Productivity In JDK8Improved Developer Productivity In JDK8
Improved Developer Productivity In JDK8Simon 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
 
Lambda: A Peek Under The Hood - Brian Goetz
Lambda: A Peek Under The Hood - Brian GoetzLambda: A Peek Under The Hood - Brian Goetz
Lambda: A Peek Under The Hood - Brian GoetzJAX London
 
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)
 
Novidades do Java SE 8
Novidades do Java SE 8Novidades do Java SE 8
Novidades do Java SE 8Bruno Borges
 
10 Tips for Java EE 7 with PrimeFaces - JavaOne 2013
10 Tips for Java EE 7 with PrimeFaces - JavaOne 201310 Tips for Java EE 7 with PrimeFaces - JavaOne 2013
10 Tips for Java EE 7 with PrimeFaces - JavaOne 2013Martin Fousek
 
JavaOne - 10 Tips for Java EE 7 with PrimeFaces
JavaOne - 10 Tips for Java EE 7 with PrimeFacesJavaOne - 10 Tips for Java EE 7 with PrimeFaces
JavaOne - 10 Tips for Java EE 7 with PrimeFacesMert Çalışkan
 
What's new for JavaFX in JDK8 - Weaver
What's new for JavaFX in JDK8 - WeaverWhat's new for JavaFX in JDK8 - Weaver
What's new for JavaFX in JDK8 - WeaverCodemotion
 
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
 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 itiAhmed mar3y
 
ADBA (Asynchronous Database Access)
ADBA (Asynchronous Database Access)ADBA (Asynchronous Database Access)
ADBA (Asynchronous Database Access)Logico
 
Batch Applications for the Java Platform
Batch Applications for the Java PlatformBatch Applications for the Java Platform
Batch Applications for the Java PlatformSivakumar Thyagarajan
 

Similar to Lambdas and-streams-s ritter-v3 (20)

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
 
Lambdas And Streams in JDK8
Lambdas And Streams in JDK8Lambdas And Streams in JDK8
Lambdas And Streams in JDK8
 
Improved Developer Productivity In JDK8
Improved Developer Productivity In JDK8Improved Developer Productivity In JDK8
Improved Developer Productivity In JDK8
 
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
 
Lambda: A Peek Under The Hood - Brian Goetz
Lambda: A Peek Under The Hood - Brian GoetzLambda: A Peek Under The Hood - Brian Goetz
Lambda: A Peek Under The Hood - Brian Goetz
 
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
 
Novidades do Java SE 8
Novidades do Java SE 8Novidades do Java SE 8
Novidades do Java SE 8
 
10 Tips for Java EE 7 with PrimeFaces - JavaOne 2013
10 Tips for Java EE 7 with PrimeFaces - JavaOne 201310 Tips for Java EE 7 with PrimeFaces - JavaOne 2013
10 Tips for Java EE 7 with PrimeFaces - JavaOne 2013
 
JavaOne - 10 Tips for Java EE 7 with PrimeFaces
JavaOne - 10 Tips for Java EE 7 with PrimeFacesJavaOne - 10 Tips for Java EE 7 with PrimeFaces
JavaOne - 10 Tips for Java EE 7 with PrimeFaces
 
What's new for JavaFX in JDK8 - Weaver
What's new for JavaFX in JDK8 - WeaverWhat's new for JavaFX in JDK8 - Weaver
What's new for JavaFX in JDK8 - Weaver
 
Java 8 Overview
Java 8 OverviewJava 8 Overview
Java 8 Overview
 
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-revealed
Java 8-revealedJava 8-revealed
Java 8-revealed
 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 iti
 
14274730 (1).ppt
14274730 (1).ppt14274730 (1).ppt
14274730 (1).ppt
 
Colloquium Report
Colloquium ReportColloquium Report
Colloquium Report
 
ADBA (Asynchronous Database Access)
ADBA (Asynchronous Database Access)ADBA (Asynchronous Database Access)
ADBA (Asynchronous Database Access)
 
Batch Applications for the Java Platform
Batch Applications for the Java PlatformBatch Applications for the Java Platform
Batch Applications for the Java Platform
 
Lambdas in Java 8
Lambdas in Java 8Lambdas in Java 8
Lambdas in Java 8
 

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

Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfIdiosysTechnologies1
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 

Recently uploaded (20)

Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdf
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdf
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 

Lambdas and-streams-s ritter-v3

  • 1. Platinum Sponsor RETHINKING YOUR CODE WITH LAMBDAS & STREAMS IN JAVA SE 8 Simon Ritter, Oracle @speakjava
  • 2. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.2 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.
  • 3. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.3 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 1.4 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 © 2012, Oracle and/or its affiliates. All rights reserved.4 Lambdas In Java
  • 5. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.5 The Problem: External Iteration List<Student> students = ... double highestScore = 0.0; for (Student s : students) { if (s.gradYear == 2011) { if (s.score > highestScore) { highestScore = s.score; } } } • Our code controls iteration • Inherently serial: iterate from beginning to end • Not thread-safe because business logic is stateful (mutable accumulator variable)
  • 6. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.6 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, Fluent List<Student> students = ... 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 © 2012, Oracle and/or its affiliates. All rights reserved.7 Internal Iteration With Lambdas SomeList<Student> students = ... double highestScore = students. filter(Student s -> s.getGradYear() == 2011). map(Student s -> s.getScore()). max(); • More readable • More abstract • Less error-prone
  • 8. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.8 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 © 2012, Oracle and/or its affiliates. All rights reserved.9 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 © 2012, Oracle and/or its affiliates. All rights reserved.10 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 fina void expire(File root, long before) { root.listFiles(File p -> p.lastModified() <= before); }
  • 11. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.11 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 class SessionManager { long before = ...; void expire(File root) { // refers to ‘this.before’, just like outside the lambda root.listFiles(File p -> checkExpiry(p.lastModified(), this.before)); } boolean checkExpiry(long time, long expiry) { ... } }
  • 12. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.12 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 © 2012, Oracle and/or its affiliates. All rights reserved.13 Method References • Method references let us reuse a method as a lambda expression FileFilter x = File f -> f.canRead(); FileFilter x = File::canRead;
  • 14. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.14 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>(); Equivalent to
  • 15. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.15 Library Evolution
  • 16. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.16 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);
  • 17. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.17 Solution: Extension 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 AKA Defender or Default Methods interface Collection<E> { default Stream<E> stream() { return StreamSupport.stream(spliterator()); } }
  • 18. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.18 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!
  • 19. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.19 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  Interfaces can now have static methods  @FunctionalInterface annotation – Helps ensure the functional interface contract is honoured – Compiler error if not a SAM
  • 20. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.20 Lambdas In Full Flow: Streams
  • 21. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.21 Aggregate Operations  Most business logic is about aggregate operations – “Most profitable product by region” – “Group transactions by currency”  As we have seen, up to now, Java uses external iteration – Inherently serial – Frustratingly imperative  Java SE 8’s answer: The Stream API – With help from Lambdas
  • 22. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.22 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
  • 23. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.23 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 sum = transactions.stream(). filter(t -> t.getBuyer().getCity().equals(“London”)). mapToInt(Transaction::getPrice). sum(); Source Intermediate operation Terminal operation
  • 24. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.24 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
  • 25. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.25 Stream Sources Provide  Access to stream elements  Decomposition (for parallel operations) – Fork-join framework  Stream characteristics – ORDERED – DISTINCT – SORTED – SIZED – NONNULL – IMMUTABLE – CONCURRENT
  • 26. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.26 Stream Terminal Operations  Invoking a terminal operation executes the pipeline – All operations can execute sequentially or in parallel  Terminal operations can take advantage of pipeline characteristics – toArray() can avoid copying for SIZED pipelines by allocating in advance
  • 27. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.27 map and flatMap Map Values in a Stream  map (one to one) – Each element of the input stream is mapped to an element in the output stream  flatMap (one to many) – Each element of the input stream is mapped to a new stream – Streams from all elements are concatenated to form one output stream
  • 28. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.28 Optional<T> Reducing NullPointerException Occurrences String direction = gpsData.getPosition().getLatitude().getDirection(); String direction = “UNKNOWN”; if (gpsData != null) { Position p = gpsData.getPosition(); if (p != null) { Latitude latitude = p.getLatitude(); if (latitude != null) direction = latitude.getDirection(); } } String direction = gpsData.getPosition().getLatitude().getDirection();
  • 29. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.29 Optional<T>  Indicates that reference may, or may not have a value – Makes developer responsible for checking – A bit like a stream that can only have zero or one elements Reducing NullPointerException Occurrences Optional<GPSData> maybeGPS = Optional.ofNullable(gpsData); maybeGPS.ifPresent(GPSData::printPosition); GPSData gps = maybeGPS.orElse(new GPSData()); maybeGPS.filter(g -> g.lastRead() < 2).ifPresent(GPSData.display());
  • 30. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.30 Example 1 Convert words in list to upper case List<String> output = wordList. stream(). map(String::toUpperCase). collect(Collectors.toList());
  • 31. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.31 Example 1 Convert words in list to upper case (in parallel) List<String> output = wordList. parallelStream(). map(String::toUpperCase). collect(Collectors.toList());
  • 32. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.32 Example 2 Find words in list with even length List<String> output = wordList. parallelStream(). filter(w -> (w.length() & 1 == 0). collect(Collectors.toList());
  • 33. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.33 Example 3  BufferedReader has new method – Stream<String> lines() Count lines in a file long count = bufferedReader. lines(). count();
  • 34. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.34 Example 4 Join lines 3-4 into a single string String output = bufferedReader. lines(). skip(2). limit(2). collect(Collectors.joining());
  • 35. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.35 Example 6 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());
  • 36. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.36 Example 7 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());
  • 37. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.37 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. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.38 Graphic Section Divider