SlideShare a Scribd company logo
Java 8 Lambda and Streams
Agenda
• Java 8
• Lambdas
• Method References
• Default Methods
Lambda
• Stream Operations
• Intermediate vs. Terminal
• Stateless vs. Stateful
• Short-Circuiting
• Collectors
• Parallel Streams
• Benchmark Sequential and Paralllel stream
Stream
Java-style functional programming
CollectionsStreams
Functional
interfaces
Functional
Java
Java™ SE 8 Release Contents
 JSR 335: Lambda Expressions
closures
 JEP 107: Bulk Data Operations for Collections
for-each
filter
map
reduce
http://www.jcp.org/en/jsr/detail?id=337
http://openjdk.java.net/jeps/107
Object
Oriented
ReflectiveStructured Functional
Generic
Concurrent GenericImperative
“…Is a blend of imperative and
object oriented programming
enhanced with functional flavors”
Java 8 Lambda and Streams
 Lambda expression is like a method –params, body
 Parameters – declared or inferred type
 (int x) -> x +1
 (x) -> x+1
 Lambda body – single expression or block
 Unlike anonymous class, this correspond to encl0sing class
 Any local variable used in lambda body must be declared final or
effectively final
 void m1(int x) { int y = 1; foo(() -> x+y); // Legal: x and y are both
effectively final. }
 A local variable or a method, constructor, lambda, or exception
parameter is effectively final if it is not final but it never occurs as the
left hand operand of an assignment operator (15.26) or as the operand of
an increment or decrement operator
void m6(int x) { foo(() -> x+1); x++; // Illegal: x is not effectively final. }
Lambda Syntax
/* argument list */
(int x, int y) -> { return x*y; }
(x, y) -> { return x*y; }
x -> { return x*2; }
() -> { System.out.println("Do you think this will work?"); }
() -> {throw new RuntimeException();}
/* single expression */
b -> { b.getMissingPages() > threshold ? b.setCondition(BAD)
: b.setCondition(GOOD) }
/* list of statements */
b -> {
Condition c = computeCondition(b.getMissingPages());
b.setCondition(c);
}
FewcommonusagesofLambdaexpression
Anonymous Class
Event Handling
Iterate over List
Parallel processing of Collection elements at API
level
Functional Programming
Streams(Collection) - Map , Reduce, Filter …
Lambda expression vs Anonymous
Classes
 this keyword
 What they are compiled into?
Functional Interfaces(FI)
• Lambdas are backed by interfaces
• Single abstract methods
• Functional Interface = Interface w/ 1 Method
• Names of Interface and Method are irrelevant
• Java API defines FI in java.util.function package
@FunctionalInterface
public interface Calculator
{
int calculate(int x, int y);
}
Calculator multiply = (x, y) -> x * y;
Calculator divide = (x, y) -> x / y;
int product = multiply.calculate(10, 20);
int quotient = divide.calculate(10, 20);
someMethod(multiply, divide);
anotherMethod((x, y) -> x ^ y);
 interface Runnable { void run(); }
// Functional
 interface Foo { boolean equals(Object obj); }
// Not functional; equals is already an implicit member
 interface Bar extends Foo { int compare(String o1, String o2);
}
// Functional; Bar has one abstract non-Object method
 interface Comparator<T> {
boolean equals(Object obj);
int compare(T o1, T o2);
}
// Functional; Comparator has one abstract non-Object method
Functional Interfaces
Function <T, R>
R apply(T t);
Supplier<T
>
T get()
Functional
Interfaces
Consumer
Function
Predicate
Supplier
Consumer<T>
void accept(T t);
Predicate<T>
boolean test(T
t);
Some usages of FI in JavaAPI
 Consumer
Iterable.forEach(Consumer<? super T> action)
 Supplier
ThreadLocal(Supplier<T> supplier)
 Predicate
Conditions like AND, OR, NEGATE, TEST…
ArrayList.removeIf(Predicate<? super E> filter)
public static void filter(List<?> names, Predicate<Object> condition)
{ names.stream().filter((name) ->
(condition.test(name))).forEach((name) -> { System.out.println(name +
" "); }); }
 Function
Comparator
Collections.sort(empList, (Employee e1, Employee e2) ->
e1.id.compareTo(e2.id));
Java 8 Lambda and Streams
Method References
books.forEach(b -> b.fixSpellingErrors());
books.forEach(Book::fixSpellingErrors); // instance method
books.forEach(b -> BookStore.generateISBN(b));
books.forEach(BookStore::generateISBN); // static method
books.forEach(b -> System.out.println(b.toString()));
books.forEach(System.out::println); // expression
Stream<ISBN> isbns1 = books.map(b -> new ISBN(b));
Stream<ISBN> isbns2 = books.map(ISBN::new); // constructor
Java 8 Lambda and Streams
Default methods
 Default methods enable new functionality to be
added to the interfaces of libraries and ensure binary
compatibility with code written for older versions of
those interfaces.
@FunctionalInterface
public interface Calculator
{
int calculate(int x, int y);
default int multiply(int x, int y)
{
return x * y;
}
}
• Can be overloaded
• Can be static or instance based
• Introduce multiple inheritance
interface java.lang.Iterable<T> {
abstract Iterator<T> iterator();
default void forEach(Consumer<? super T> consumer) {
for (T t : this) {
consumer.accept(t);
}
}
}
java.lang.Iterable<Object> i = () ->
java.util.Collection.emptyList().iterator();
Operation 1
Operation
2
Operation
3
Operation
4
Stream
Lambda Lambda Lambda Lambda
Streams
 A pipes-and-filters based API for collections
This may be familiar...
ps -ef | grep java | cut -c 1-9 | sort -n | uniq
 A Stream is an abstraction that represents zero or more values (not objects)
 Pipelines
A stream source
Zero or more intermediate operations
a terminal operations
A pipeline can be executed in parallel
 interface java.util.stream.Stream<T>
forEach()
filter()
map()
reduce()
…
 java.util.Collection<T>
Stream<T> stream()
Stream<T> parallelStream()
Streams can be obtained in a number of ways. Some examples include:
• From a Collection via the stream() and parallelStream() methods;
• From an array via Arrays.stream(Object[]);
• From static factory methods on the stream classes, such as
Stream.of(Object[]), IntStream.range(int, int) or Stream.iterate(Object,
UnaryOperator);
• The lines of a file can be obtained from BufferedReader.lines();
• Streams of file paths can be obtained from methods in Files;
• Streams of random numbers can be obtained from Random.ints();
• Numerous other stream-bearing methods in the JDK, including
BitSet.stream(), Pattern.splitAsStream(java.lang.CharSequence), and
JarFile.stream().
Creating and using a Stream
List<Book> myBooks = …;
Stream<Book> books = myBooks.stream();
Stream<Book> goodBooks =
books.filter(b -> b.getStarRating() > 3);
goodBooks.forEach(b -> System.out.println(b.toString()));
Properties of Streams
 Streams do not store elements…
…they are a view on top of a data structure
 Operations provided by Streams...
…are applied to the underlying data source elements
 Stream Operations can take as a parameter…
…Lambda expressions
…Method references
 Manipulating the underlying data source...
…will yield a ConcurrentModificationException
Java 8 Lambda and Streams
Stream Operations
builder() Returns a builder for a Stream.
filter(Predicate<? super T> predicate) Returns a stream consisting of the
elements of this stream that match the given predicate.
flatMap(Function<? super T,? extends Stream<? extends R>> mapper) Returns a
stream consisting of the results of replacing each element of this stream with
the contents of a mapped stream produced by applying the provided mapping
function to each element.
reduce(BinaryOperator<T> accumulator) Performs a reduction on the elements
of this stream, using an associative accumulation function, and returns an
Optional describing the reduced value, if any.
iterate(T seed, UnaryOperator<T> f) Returns an infinite sequential ordered
Stream produced by iterative application of a function f to an initial element
seed, producing a Stream consisting of seed, f(seed), f(f(seed)), etc.
peek(Consumer<? super T> action) Returns a stream consisting of the elements
of this stream, additionally performing the provided action on each element as
elements are consumed from the resulting stream.
Stream
operations
Build
Filter
Map
Reduce
Iterate
Peek
Java 8 Lambda and Streams
Intermediate vs. Terminal
 Intermediate: Output is another Stream
filter()
map()
…
 Terminal: Do something else with the Stream
forEach()
reduce()
…
double totalPrice = books.mapToDouble(Book::getPrice)
.reduce(0.0, (p1, p2) -> p1+p2);
Stream Evaluation
 Intermediate Streams are not evaluated…
…until a Terminal Operation is invoked on them
 Intermediate = Lazy
 Terminal = Eager (Consuming)
 This allows Java to…
…do some code optimization during compilation
…avoid buffering intermediate Streams
…handle parallel Streams more easily
Java 8 Lambda and Streams
Stateless Intermediate Operations
 Operation need nothing other than the current Stream
element to perform its work
 Examples
map()  Maps element to something else
filter()  Apply predicate and keep or drop element
List<Book> myBooks = ...;
double impairments = myBooks.stream()
.filter(b -> b.getCondition().equals(BAD))
.mapToDouble(Book::getPrice)
.reduce(0.0, (p1, p2) -> p1 + p2);
Stateful Intermediate Operations
 Operations that require not only the current stream element
but also additional state
distinct()  Element goes to next stage if it appears the first time
sorted()  Sort elements into natural order
sorted(Comparator)  Sort according to provided Comparator
substream(long)  Discard elements up to provided offset
substream(long, long)  Keep only elements in between offsets
limit(long)  Discard any elements after the provided max. size
myBooks.stream().map(Book::getAuthor).distinct().forEach(System.out::println);
Java 8 Lambda and Streams
Short-Circuiting Operations
 Processing might stop before the last element of the
Stream is reached
Intermediate
limit(long)
substream(long, long)
Terminal
anyMatch(Predicate)
allMatch(Predicate)
noneMatch(Predicate)
findFirst()
findAny()
Author rp = new Author("Rosamunde Pilcher");
boolean phew = myBooks.stream()
.map(Book::getAuthor)
.noneMatch(isEqual(rp));
System.out.println("Am I safe? " + phew);
Java 8 Lambda and Streams
Collectors
 <R> R collect(Collector<? super T, A, R> col)
Collect the elements of a Stream into some other data
structure
Powerful and complex tool
Collector is not so easy to implement, but…
 …luckily there are lots of factory methods for everyday
use in java.util.stream.Collectors
toList()
toSet()
toCollection(Supplier)
toMap(Function, Function)
…
Collector Examples
List<Author> authors = myBooks.stream()
.map(Book::getAuthor)
.collect(Collectors.toList());
double averagePages = myBooks.stream()
.collect(Collectors.averagingInt(Book::getPages));
Java 8 Lambda and Streams
Parallel Streams
• Uses fork-join used under the hood
• Thread pool sized to # cores
• Order can be changed
Parallel Streams
Imperative
Serial
Stream
Parallel
Stream
8,128 0 1 0
33,550,336 190 229 66
8,589,869,056 48648 59646 13383
137,438,691,328 778853 998776 203651
private static boolean isPerfect(long n)
{
return n > 0 &&
LongStream.rangeClosed(1, n / 2). parallel().
filter(i -> n % i == 0).
reduce(0, (l, r) -> l + r) == n;
}
List<Long> perfectNumbers =
LongStream.rangeClosed(1, 8192).parallel().
filter(PerfectNumberFinder::isPerfect).
collect(ArrayList<Long>::new, ArrayList<Long>::add, ArrayList<Long>::addAll);
Parallelization
• Must avoid side-effects and mutating
state
• Problems must fit the associativity
property
• Ex: ((a * b) * c) = (a * (b * c))
• Must be enough parallelizable code
• Performance not always better
• Can’t modify local variables (unlike for
loops)
Streams
Good
• Allow abstraction of details
• Communicate intent clearly
• Concise
• On-demand parallelization
Bad
• Loss of flexibility and control
• Increased code density
• Can be less efficient
• On-demand parallelization
Java 8 Lambda and Streams
Java 8 Lambda and Streams
 Lambda expressions
 Remove the Permanent Generation
 Small VM
 Parallel Array Sorting
 Bulk Data Operations for Collections
 Define a standard API for Base64 encoding and
decoding
 New Date & Time API
 Provide stronger Password-Based-Encryption (PBE)
algorithm implementations in the SunJCE provider
Optional
 One interesting new class, used in the Stream API, is
Optional in java.util.
 It is basically an alternative to using null explicitly - it is
returned by some stream operators when it is not
certain that there is a result (e.g. when reducing).
 To check whether it has any contents, isPresent can be
called. If an Option has contents, get will return it.
SoundCard soundcard = ...;
if(soundcard != null){
System.out.println(soundcard);
}
You can use the ifPresent() method, as follows:
Optional<Soundcard> soundcard = ...;
soundcard.ifPresent(System.out::println);
Spliterator
 A spliterator is the parallel analogue of an Iterator; it
describes a (possibly infinite) collection of elements, with
support for sequentially advancing, bulk traversal, and
splitting off some portion of the input into another
spliterator which can be processed in parallel.
 At the lowest level, all streams are driven by a spliterator.
 To support the parallel execution of the pipeline, the data
elements in the original collection must be split over multiple
threads.
 The Spliterator interface, also in java.util, provides this
functionality.
 The method trySplit returns a new Spliterator that manages a
subset of the elements of the original Spliterator. The original
Spliterator then skips elements in the subset that was
delegated. An ideal Spliterator might delegate the
management of half of its elements to a new Spliterator (up
to a certain threshold), so that users can easily break down
the set of data, e.g. for parallelization purposes.
Joining Collector
 Used for concatenation of CharSequences
 Internally implemented using StringBuilder
A lot more efficient than a Map-Reduce with
intermediately concatenated Strings
// not efficient due to recursive String concatenation. And ugly.
String titleList = myBooks.stream().map(Book::getTitle).reduce("", (t1, t2) -> t1+t2);
// Still inefficient. Still ugly (initial line break)
titleList = myBooks.stream().map(Book::getTitle).reduce("", (t1, t2) -> t1+"n"+t2);
// more efficient thanks to StringBuilder. Pretty printed.
titleList = myBooks.stream().map(Book::getTitle).collect(Collectors.joining("n"));
Projects based on Lambda and
streams
 Apache Spark
 Spring-io sagan
 Jlinq (http://www.jinq.org/)
Java 8 Lambda and Streams
Functional Interfaces
 There will be also new functional interfaces, such as
Predicate<T> and Block<T>
 Default: java.util.function.Consumer<T>
public interface Stream<T> {
void forEach(Consumer<? super T> consumer);
}
public interface Consumer<T> {void accept(T t);}
Consumer<Book> reduceRankForBadAuthors =
(Book b) -> { if (b.getStarRating() < 2) b.getAuthor().addRank(-1); };
books.forEach(reduceRankForBadAuthors);
books.forEach(b -> b.setEstimatedReadingTime(90*b.getPages()));
Terminal = Consuming Operations
 Intermediate Operations can be chained
 Only one Terminal Operation can be invoked
 Best avoid reference variables to Streams entirely by
using Fluent Programming
Construction  (Intermediate)*  Terminal;
books.forEach(b -> System.out.println("Book: " + b.getTitle()));
double totalPrice = books.reduce(0.0, (b1, b2)
-> b1.getPrice() + b2.getPrice());
Exception in thread "main" java.lang.IllegalStateException:
stream has already been operated upon or closed

More Related Content

PPTX
Java 8 presentation
PDF
Java 8 Stream API. A different way to process collections.
PDF
Java 8 Lambda Expressions
PPTX
Java 8 lambda
PPT
Java 8 Streams
ODP
Java 9 Features
PDF
Java 8 features
PPTX
Java Lambda Expressions.pptx
Java 8 presentation
Java 8 Stream API. A different way to process collections.
Java 8 Lambda Expressions
Java 8 lambda
Java 8 Streams
Java 9 Features
Java 8 features
Java Lambda Expressions.pptx

What's hot (20)

PDF
Hibernate Presentation
PPTX
PDF
JPA and Hibernate
PDF
Collections In Java
PDF
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
PPTX
Introduction to java 8 stream api
PDF
REST APIs with Spring
PPTX
Spring Boot Tutorial
PPTX
Java - Collections framework
PDF
Java 8 Lambda Expressions & Streams
PPTX
java 8 new features
PDF
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
PDF
Streams in Java 8
PDF
PPTX
Introduction to spring boot
PPT
Java Collections Framework
PDF
JavaScript Basics and Best Practices - CC FE & UX
PDF
Java 8 Lambda Built-in Functional Interfaces
PDF
Java Collection framework
PPSX
Spring - Part 1 - IoC, Di and Beans
Hibernate Presentation
JPA and Hibernate
Collections In Java
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Introduction to java 8 stream api
REST APIs with Spring
Spring Boot Tutorial
Java - Collections framework
Java 8 Lambda Expressions & Streams
java 8 new features
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
Streams in Java 8
Introduction to spring boot
Java Collections Framework
JavaScript Basics and Best Practices - CC FE & UX
Java 8 Lambda Built-in Functional Interfaces
Java Collection framework
Spring - Part 1 - IoC, Di and Beans
Ad

Viewers also liked (15)

PPTX
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
PDF
Lambda Expressions in Java
PPT
55 New Features in Java 7
PDF
Java 8 Lambda
PDF
PDF
50 new things you can do with java 8
PDF
Java 8-streams-collectors-patterns
PDF
50 nouvelles choses que l'on peut faire avec Java 8
PDF
Java 8, Streams & Collectors, patterns, performances and parallelization
PDF
Java SE 8 best practices
PDF
Les Streams sont parmi nous
PDF
Java 8 : Un ch'ti peu de lambda
PPTX
New Features in JDK 8
PDF
Retours sur java 8 devoxx fr 2016
PPTX
55 New Features in Java SE 8
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
Lambda Expressions in Java
55 New Features in Java 7
Java 8 Lambda
50 new things you can do with java 8
Java 8-streams-collectors-patterns
50 nouvelles choses que l'on peut faire avec Java 8
Java 8, Streams & Collectors, patterns, performances and parallelization
Java SE 8 best practices
Les Streams sont parmi nous
Java 8 : Un ch'ti peu de lambda
New Features in JDK 8
Retours sur java 8 devoxx fr 2016
55 New Features in Java SE 8
Ad

Similar to Java 8 Lambda and Streams (20)

PDF
Charles Sharp: Java 8 Streams
PDF
Java Lambda internals with invoke dynamic
PDF
Lambda.pdf
PPTX
Java8 training - Class 1
PPTX
Java 8
PPTX
Java 8 streams
PDF
Apouc 2014-java-8-create-the-future
PPTX
PDF
Harnessing the Power of Java 8 Streams
PPTX
A brief tour of modern Java
PPTX
Lambdas and-streams-s ritter-v3
PDF
Java 8 Workshop
PPTX
JDK8 Lambdas and Streams: Changing The Way You Think When Developing Java
PPTX
java150929145120-lva1-app6892 (2).pptx
PPTX
Functional Programming With Lambdas and Streams in JDK8
PPTX
A Brief Conceptual Introduction to Functional Java 8 and its API
PPTX
Lambdas And Streams Hands On Lab, JavaOne 2014
PPTX
Lambdas : Beyond The Basics
PDF
Java 8 - functional features
PPTX
Java 8 Streams And Common Operations By Harmeet Singh(Taara)
Charles Sharp: Java 8 Streams
Java Lambda internals with invoke dynamic
Lambda.pdf
Java8 training - Class 1
Java 8
Java 8 streams
Apouc 2014-java-8-create-the-future
Harnessing the Power of Java 8 Streams
A brief tour of modern Java
Lambdas and-streams-s ritter-v3
Java 8 Workshop
JDK8 Lambdas and Streams: Changing The Way You Think When Developing Java
java150929145120-lva1-app6892 (2).pptx
Functional Programming With Lambdas and Streams in JDK8
A Brief Conceptual Introduction to Functional Java 8 and its API
Lambdas And Streams Hands On Lab, JavaOne 2014
Lambdas : Beyond The Basics
Java 8 - functional features
Java 8 Streams And Common Operations By Harmeet Singh(Taara)

More from Venkata Naga Ravi (12)

PPTX
Microservices with Docker
PPTX
Processing Large Data with Apache Spark -- HasGeek
PPTX
Quick Trip with Docker
PPTX
Glint with Apache Spark
PPTX
PPTX
Big Data Benchmarking
PPTX
PPTX
Kubernetes
PPTX
NoSQL & HBase overview
PPTX
Software Defined Network - SDN
PPTX
Virtual Container - Docker
PPTX
In Memory Analytics with Apache Spark
Microservices with Docker
Processing Large Data with Apache Spark -- HasGeek
Quick Trip with Docker
Glint with Apache Spark
Big Data Benchmarking
Kubernetes
NoSQL & HBase overview
Software Defined Network - SDN
Virtual Container - Docker
In Memory Analytics with Apache Spark

Recently uploaded (20)

PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PDF
top salesforce developer skills in 2025.pdf
PPTX
Operating system designcfffgfgggggggvggggggggg
PDF
Softaken Excel to vCard Converter Software.pdf
PDF
Digital Strategies for Manufacturing Companies
PPTX
Online Work Permit System for Fast Permit Processing
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PDF
System and Network Administraation Chapter 3
PDF
AI in Product Development-omnex systems
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
How Creative Agencies Leverage Project Management Software.pdf
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PDF
medical staffing services at VALiNTRY
PPTX
Odoo POS Development Services by CandidRoot Solutions
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PPTX
history of c programming in notes for students .pptx
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
top salesforce developer skills in 2025.pdf
Operating system designcfffgfgggggggvggggggggg
Softaken Excel to vCard Converter Software.pdf
Digital Strategies for Manufacturing Companies
Online Work Permit System for Fast Permit Processing
VVF-Customer-Presentation2025-Ver1.9.pptx
Adobe Illustrator 28.6 Crack My Vision of Vector Design
System and Network Administraation Chapter 3
AI in Product Development-omnex systems
Internet Downloader Manager (IDM) Crack 6.42 Build 41
How Creative Agencies Leverage Project Management Software.pdf
CHAPTER 2 - PM Management and IT Context
Navsoft: AI-Powered Business Solutions & Custom Software Development
medical staffing services at VALiNTRY
Odoo POS Development Services by CandidRoot Solutions
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
Odoo Companies in India – Driving Business Transformation.pdf
history of c programming in notes for students .pptx

Java 8 Lambda and Streams

  • 2. Agenda • Java 8 • Lambdas • Method References • Default Methods Lambda • Stream Operations • Intermediate vs. Terminal • Stateless vs. Stateful • Short-Circuiting • Collectors • Parallel Streams • Benchmark Sequential and Paralllel stream Stream
  • 4. Java™ SE 8 Release Contents  JSR 335: Lambda Expressions closures  JEP 107: Bulk Data Operations for Collections for-each filter map reduce http://www.jcp.org/en/jsr/detail?id=337 http://openjdk.java.net/jeps/107
  • 5. Object Oriented ReflectiveStructured Functional Generic Concurrent GenericImperative “…Is a blend of imperative and object oriented programming enhanced with functional flavors”
  • 7.  Lambda expression is like a method –params, body  Parameters – declared or inferred type  (int x) -> x +1  (x) -> x+1  Lambda body – single expression or block  Unlike anonymous class, this correspond to encl0sing class  Any local variable used in lambda body must be declared final or effectively final  void m1(int x) { int y = 1; foo(() -> x+y); // Legal: x and y are both effectively final. }  A local variable or a method, constructor, lambda, or exception parameter is effectively final if it is not final but it never occurs as the left hand operand of an assignment operator (15.26) or as the operand of an increment or decrement operator void m6(int x) { foo(() -> x+1); x++; // Illegal: x is not effectively final. }
  • 8. Lambda Syntax /* argument list */ (int x, int y) -> { return x*y; } (x, y) -> { return x*y; } x -> { return x*2; } () -> { System.out.println("Do you think this will work?"); } () -> {throw new RuntimeException();} /* single expression */ b -> { b.getMissingPages() > threshold ? b.setCondition(BAD) : b.setCondition(GOOD) } /* list of statements */ b -> { Condition c = computeCondition(b.getMissingPages()); b.setCondition(c); }
  • 9. FewcommonusagesofLambdaexpression Anonymous Class Event Handling Iterate over List Parallel processing of Collection elements at API level Functional Programming Streams(Collection) - Map , Reduce, Filter …
  • 10. Lambda expression vs Anonymous Classes  this keyword  What they are compiled into?
  • 11. Functional Interfaces(FI) • Lambdas are backed by interfaces • Single abstract methods • Functional Interface = Interface w/ 1 Method • Names of Interface and Method are irrelevant • Java API defines FI in java.util.function package @FunctionalInterface public interface Calculator { int calculate(int x, int y); } Calculator multiply = (x, y) -> x * y; Calculator divide = (x, y) -> x / y; int product = multiply.calculate(10, 20); int quotient = divide.calculate(10, 20); someMethod(multiply, divide); anotherMethod((x, y) -> x ^ y);
  • 12.  interface Runnable { void run(); } // Functional  interface Foo { boolean equals(Object obj); } // Not functional; equals is already an implicit member  interface Bar extends Foo { int compare(String o1, String o2); } // Functional; Bar has one abstract non-Object method  interface Comparator<T> { boolean equals(Object obj); int compare(T o1, T o2); } // Functional; Comparator has one abstract non-Object method
  • 13. Functional Interfaces Function <T, R> R apply(T t); Supplier<T > T get() Functional Interfaces Consumer Function Predicate Supplier Consumer<T> void accept(T t); Predicate<T> boolean test(T t);
  • 14. Some usages of FI in JavaAPI  Consumer Iterable.forEach(Consumer<? super T> action)  Supplier ThreadLocal(Supplier<T> supplier)  Predicate Conditions like AND, OR, NEGATE, TEST… ArrayList.removeIf(Predicate<? super E> filter) public static void filter(List<?> names, Predicate<Object> condition) { names.stream().filter((name) -> (condition.test(name))).forEach((name) -> { System.out.println(name + " "); }); }  Function Comparator Collections.sort(empList, (Employee e1, Employee e2) -> e1.id.compareTo(e2.id));
  • 16. Method References books.forEach(b -> b.fixSpellingErrors()); books.forEach(Book::fixSpellingErrors); // instance method books.forEach(b -> BookStore.generateISBN(b)); books.forEach(BookStore::generateISBN); // static method books.forEach(b -> System.out.println(b.toString())); books.forEach(System.out::println); // expression Stream<ISBN> isbns1 = books.map(b -> new ISBN(b)); Stream<ISBN> isbns2 = books.map(ISBN::new); // constructor
  • 18. Default methods  Default methods enable new functionality to be added to the interfaces of libraries and ensure binary compatibility with code written for older versions of those interfaces. @FunctionalInterface public interface Calculator { int calculate(int x, int y); default int multiply(int x, int y) { return x * y; } } • Can be overloaded • Can be static or instance based • Introduce multiple inheritance interface java.lang.Iterable<T> { abstract Iterator<T> iterator(); default void forEach(Consumer<? super T> consumer) { for (T t : this) { consumer.accept(t); } } } java.lang.Iterable<Object> i = () -> java.util.Collection.emptyList().iterator();
  • 20. Streams  A pipes-and-filters based API for collections This may be familiar... ps -ef | grep java | cut -c 1-9 | sort -n | uniq  A Stream is an abstraction that represents zero or more values (not objects)  Pipelines A stream source Zero or more intermediate operations a terminal operations A pipeline can be executed in parallel  interface java.util.stream.Stream<T> forEach() filter() map() reduce() …  java.util.Collection<T> Stream<T> stream() Stream<T> parallelStream()
  • 21. Streams can be obtained in a number of ways. Some examples include: • From a Collection via the stream() and parallelStream() methods; • From an array via Arrays.stream(Object[]); • From static factory methods on the stream classes, such as Stream.of(Object[]), IntStream.range(int, int) or Stream.iterate(Object, UnaryOperator); • The lines of a file can be obtained from BufferedReader.lines(); • Streams of file paths can be obtained from methods in Files; • Streams of random numbers can be obtained from Random.ints(); • Numerous other stream-bearing methods in the JDK, including BitSet.stream(), Pattern.splitAsStream(java.lang.CharSequence), and JarFile.stream().
  • 22. Creating and using a Stream List<Book> myBooks = …; Stream<Book> books = myBooks.stream(); Stream<Book> goodBooks = books.filter(b -> b.getStarRating() > 3); goodBooks.forEach(b -> System.out.println(b.toString()));
  • 23. Properties of Streams  Streams do not store elements… …they are a view on top of a data structure  Operations provided by Streams... …are applied to the underlying data source elements  Stream Operations can take as a parameter… …Lambda expressions …Method references  Manipulating the underlying data source... …will yield a ConcurrentModificationException
  • 25. Stream Operations builder() Returns a builder for a Stream. filter(Predicate<? super T> predicate) Returns a stream consisting of the elements of this stream that match the given predicate. flatMap(Function<? super T,? extends Stream<? extends R>> mapper) Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element. reduce(BinaryOperator<T> accumulator) Performs a reduction on the elements of this stream, using an associative accumulation function, and returns an Optional describing the reduced value, if any. iterate(T seed, UnaryOperator<T> f) Returns an infinite sequential ordered Stream produced by iterative application of a function f to an initial element seed, producing a Stream consisting of seed, f(seed), f(f(seed)), etc. peek(Consumer<? super T> action) Returns a stream consisting of the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resulting stream. Stream operations Build Filter Map Reduce Iterate Peek
  • 27. Intermediate vs. Terminal  Intermediate: Output is another Stream filter() map() …  Terminal: Do something else with the Stream forEach() reduce() … double totalPrice = books.mapToDouble(Book::getPrice) .reduce(0.0, (p1, p2) -> p1+p2);
  • 28. Stream Evaluation  Intermediate Streams are not evaluated… …until a Terminal Operation is invoked on them  Intermediate = Lazy  Terminal = Eager (Consuming)  This allows Java to… …do some code optimization during compilation …avoid buffering intermediate Streams …handle parallel Streams more easily
  • 30. Stateless Intermediate Operations  Operation need nothing other than the current Stream element to perform its work  Examples map()  Maps element to something else filter()  Apply predicate and keep or drop element List<Book> myBooks = ...; double impairments = myBooks.stream() .filter(b -> b.getCondition().equals(BAD)) .mapToDouble(Book::getPrice) .reduce(0.0, (p1, p2) -> p1 + p2);
  • 31. Stateful Intermediate Operations  Operations that require not only the current stream element but also additional state distinct()  Element goes to next stage if it appears the first time sorted()  Sort elements into natural order sorted(Comparator)  Sort according to provided Comparator substream(long)  Discard elements up to provided offset substream(long, long)  Keep only elements in between offsets limit(long)  Discard any elements after the provided max. size myBooks.stream().map(Book::getAuthor).distinct().forEach(System.out::println);
  • 33. Short-Circuiting Operations  Processing might stop before the last element of the Stream is reached Intermediate limit(long) substream(long, long) Terminal anyMatch(Predicate) allMatch(Predicate) noneMatch(Predicate) findFirst() findAny() Author rp = new Author("Rosamunde Pilcher"); boolean phew = myBooks.stream() .map(Book::getAuthor) .noneMatch(isEqual(rp)); System.out.println("Am I safe? " + phew);
  • 35. Collectors  <R> R collect(Collector<? super T, A, R> col) Collect the elements of a Stream into some other data structure Powerful and complex tool Collector is not so easy to implement, but…  …luckily there are lots of factory methods for everyday use in java.util.stream.Collectors toList() toSet() toCollection(Supplier) toMap(Function, Function) …
  • 36. Collector Examples List<Author> authors = myBooks.stream() .map(Book::getAuthor) .collect(Collectors.toList()); double averagePages = myBooks.stream() .collect(Collectors.averagingInt(Book::getPages));
  • 38. Parallel Streams • Uses fork-join used under the hood • Thread pool sized to # cores • Order can be changed
  • 39. Parallel Streams Imperative Serial Stream Parallel Stream 8,128 0 1 0 33,550,336 190 229 66 8,589,869,056 48648 59646 13383 137,438,691,328 778853 998776 203651 private static boolean isPerfect(long n) { return n > 0 && LongStream.rangeClosed(1, n / 2). parallel(). filter(i -> n % i == 0). reduce(0, (l, r) -> l + r) == n; } List<Long> perfectNumbers = LongStream.rangeClosed(1, 8192).parallel(). filter(PerfectNumberFinder::isPerfect). collect(ArrayList<Long>::new, ArrayList<Long>::add, ArrayList<Long>::addAll);
  • 40. Parallelization • Must avoid side-effects and mutating state • Problems must fit the associativity property • Ex: ((a * b) * c) = (a * (b * c)) • Must be enough parallelizable code • Performance not always better • Can’t modify local variables (unlike for loops)
  • 41. Streams Good • Allow abstraction of details • Communicate intent clearly • Concise • On-demand parallelization Bad • Loss of flexibility and control • Increased code density • Can be less efficient • On-demand parallelization
  • 44.  Lambda expressions  Remove the Permanent Generation  Small VM  Parallel Array Sorting  Bulk Data Operations for Collections  Define a standard API for Base64 encoding and decoding  New Date & Time API  Provide stronger Password-Based-Encryption (PBE) algorithm implementations in the SunJCE provider
  • 45. Optional  One interesting new class, used in the Stream API, is Optional in java.util.  It is basically an alternative to using null explicitly - it is returned by some stream operators when it is not certain that there is a result (e.g. when reducing).  To check whether it has any contents, isPresent can be called. If an Option has contents, get will return it. SoundCard soundcard = ...; if(soundcard != null){ System.out.println(soundcard); } You can use the ifPresent() method, as follows: Optional<Soundcard> soundcard = ...; soundcard.ifPresent(System.out::println);
  • 46. Spliterator  A spliterator is the parallel analogue of an Iterator; it describes a (possibly infinite) collection of elements, with support for sequentially advancing, bulk traversal, and splitting off some portion of the input into another spliterator which can be processed in parallel.  At the lowest level, all streams are driven by a spliterator.  To support the parallel execution of the pipeline, the data elements in the original collection must be split over multiple threads.  The Spliterator interface, also in java.util, provides this functionality.  The method trySplit returns a new Spliterator that manages a subset of the elements of the original Spliterator. The original Spliterator then skips elements in the subset that was delegated. An ideal Spliterator might delegate the management of half of its elements to a new Spliterator (up to a certain threshold), so that users can easily break down the set of data, e.g. for parallelization purposes.
  • 47. Joining Collector  Used for concatenation of CharSequences  Internally implemented using StringBuilder A lot more efficient than a Map-Reduce with intermediately concatenated Strings // not efficient due to recursive String concatenation. And ugly. String titleList = myBooks.stream().map(Book::getTitle).reduce("", (t1, t2) -> t1+t2); // Still inefficient. Still ugly (initial line break) titleList = myBooks.stream().map(Book::getTitle).reduce("", (t1, t2) -> t1+"n"+t2); // more efficient thanks to StringBuilder. Pretty printed. titleList = myBooks.stream().map(Book::getTitle).collect(Collectors.joining("n"));
  • 48. Projects based on Lambda and streams  Apache Spark  Spring-io sagan  Jlinq (http://www.jinq.org/)
  • 50. Functional Interfaces  There will be also new functional interfaces, such as Predicate<T> and Block<T>  Default: java.util.function.Consumer<T> public interface Stream<T> { void forEach(Consumer<? super T> consumer); } public interface Consumer<T> {void accept(T t);} Consumer<Book> reduceRankForBadAuthors = (Book b) -> { if (b.getStarRating() < 2) b.getAuthor().addRank(-1); }; books.forEach(reduceRankForBadAuthors); books.forEach(b -> b.setEstimatedReadingTime(90*b.getPages()));
  • 51. Terminal = Consuming Operations  Intermediate Operations can be chained  Only one Terminal Operation can be invoked  Best avoid reference variables to Streams entirely by using Fluent Programming Construction  (Intermediate)*  Terminal; books.forEach(b -> System.out.println("Book: " + b.getTitle())); double totalPrice = books.reduce(0.0, (b1, b2) -> b1.getPrice() + b2.getPrice()); Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed