SlideShare a Scribd company logo
Streams in Java 8
Start programming in a more functional style
Background
Who am I?
โ€ข Tobias Coetzee
โ€ข Iโ€™m a Technical Lead at BBD
โ€ข I present the Java Expert Level Certifications at BBD (EJB,
JPA, etc.)
โ€ข Iโ€™m currently a banker
โ€ข Part of the JoziJug organising committee
โ€ข I like to run
โ€ข This partially presentation is based on a Simon Ritter
course
โ€ข @tobiascode
โ€ข https://github.com/Jozi-JUG/streamtraining
Outcomes
What are the take awayโ€™s?
โ€ข Know the differences between functional and imperative
programming
โ€ข Be able to define the elements of a stream
โ€ข Use intermediate and terminal operations
โ€ข Create streams from different data types
โ€ข Avoid NullPointerExceptions with the Optional Class
โ€ข Debug streams
What Did We Do Last
Time?
Lambdas
Summary
โ€ข CPUโ€™s are getting much faster, but we are getting more cores to use.
โ€ข Inject functionality into methods, the same way we inject values into
methods.
โ€ข Lambda syntax and rules, (parameters) -> {lambda body}
โ€ข Functional interfaces are interfaces that have only one abstract
method.
โ€ข Lambdas can be used where the type is a functional interface.
โ€ข Use lambdas as method parameters or assign them to variables.
โ€ข The java.util.function package already gives us a few functional
interfaces out of the box.
โ€ข Method and constructor references as short hands notation, ::.
โ€ข There are a few new methods that can use lambdas in Java 8, e.g.
forEach(Consumer c).
What Is Functional
Programming?
Functional Programming
Remember this game?
Functional Programming
Imperative
โ€ข Values associated with names can be changed, i.e. mutable state.
โ€ข The order of execution is defined as a contract.
โ€ข Repetition is external and explicit, we are responsible for the โ€œhowโ€.
Functional (Declarative)
โ€ข Values associated with names are set once and cannot be changed,
i.e. immutable state.
โ€ข Order of execution is not defined
โ€ข Repetition is through the use of recursion or internal repetition, the
โ€œhowโ€ is hidden away.
Thinking about a problem in terms of immutable
values and functions that translate between them.
โ€œMultithreaded programming, requiring
synchronised access to shared, mutable
state, is the assembly language of
concurrencyโ€
The Elements of a Stream
Elements of a Stream
What are streams?
โ€ข Streams give us functional blocks to better process
collections of data with, monads.
โ€ข We can chain these blocks together to process
collections of data.
โ€ข Streams arenโ€™t another data structure.
โ€ข Streams can process an infinite list of data.
โ€ข Streams use internal iteration meaning we donโ€™t have to
code external iteration, the โ€œhowโ€.
โ€ข Streams support functional programming as suppose to
imperative programming.
โ€œThe purpose of streams isnโ€™t just to convert
from one collection to another; itโ€™s to be
able to provide a common set of operations
over dataโ€
Elements of a Stream
Structure of a Stream
โ€ข A stream consists of 3 types of things
1. A source
2. Zero or more intermediate operations
3. A terminal operation
result = albums.stream()
.filter(track -> track.getLength() > 300)
.map(Track::getName)
.collect(Collectors.toSet());
Source
Intermediate
Operation
Intermediate
Operation
Terminal
Operation
Result
Demo: Refactor Code
Elements of a Stream
How they work
โ€ข The pipeline is only evaluated when the terminal
operation is called.
โ€ข The terminal operations pulls the data, the source doesnโ€™t
push it.
โ€ข Uses the stream characteristics to help identify
optimisations.
โ€ข This allows intermediate operations to be merged:
โ€ข Avoiding multiple redundant passes on data
โ€ข Short-circuit operations
โ€ข Laze evaluation
โ€ข The stream takes care of the โ€œhowโ€.
Intermediate Operations
Intermediate Operations
Intermediate
โ€ข A stream provides a sequence of elements.
โ€ข Supports either sequential or parallel aggregate
operations.
โ€ข Most operations take a parameter that describes its
behaviour, the โ€œwhatโ€.
โ€ข Typically using lambda expressions.
โ€ข Must be non-interfering
โ€ข Stateless
โ€ข Streams can switch between sequential and parallel, but
all processing is either done sequential or parallel, last
call wins.
Intermediate Operations
Filtering and Mapping
Interface Description
filter(Predicate) Returns a stream with only those elements that return
true for the Predicate
map(Function) Return a stream where the given Function is applied
to each element on the input stream
mapToInt,
mapToDouble,
mapToLong
Like map(), but producing streams of primitives rather
than objects.
distinct() Returns a stream with no duplicate elements
Intermediate Operations
Map() and FlatMap()
โ€ข Map values from a stream either as one-to-one or one-
to-many, but still only produce one stream.
map()
input stream output stream
one-to-one
flatMap()
input stream output stream
one-to-many
Intermediate Operations
Sizing and Sorting
Interface Description
skip(long) Returns a stream that skips the first n elements of
the input stream
limit(long) Return a stream that only contains the first n
elements of the input stream
sorted(Comparator) Returns a stream that is sorted with the order
determined by the Comparator.
With no arguments sorts by natural order.
unordered() Returns a stream that is unordered (used internally).
Can improve efficiency of operations like
distinct() and groupingBy()
Terminal Operations
Terminal Operations
Terminal
โ€ข Terminates the pipeline of the operations on the
stream.
โ€ข Only at this point is any processing performed.
โ€ข This allows for optimisation of the pipeline:
โ€ข Lazy evaluation
โ€ข Merged/fused operations
โ€ข Elimination of redundant operations
โ€ข Parallel execution
โ€ข Generates an explicit result of a side effect.
Intermediate Operations
Matching Elements and Iteration
Interface Description
findFirst(Predicate) The first element that matches predicate
findAny(Predicate) Like findFirst(), but for a parallel
stream
allMatch(Predicate) All elements in the stream match predicate
anyMatch(Predicate) Any element in the stream matches
predicate
noneMatch(Predicate) No elements match the predicate
forEach(Consumer) Performs an action on each element
forEachOrdered(Consumer) Like above, but ensures order is respected
when used for parallel stream
*
*
* Encourages non-functional programming style
Intermediate Operations
Collecting Results and Numerical Results
Interface Description
collect(Collector) Performs a mutable reduction on a stream
toArray() Returns an array containing the elements of the
stream
count() Returns how many elements are in the stream
max(Comparator) The maximum value element of the stream,
returns an Optional
min(Comparator) The minimum value element of the stream,
returns an Optional
average() Return the arithmetic mean of the stream, returns
an Optional
sum() Returns the sum of the stream elements
*
There are a lot of built-in Collectors
*
Terminal Operations
Creating a Single Result
โ€ข The collect function isnโ€™t the only option.
โ€ข reduce(BinaryOperator accumulator)
โ€ข Also called folding in FP.
โ€ข Performs a reduction on the stream using the
BinaryOperator.
โ€ข The accumulator takes a partial result and the next
element and returns a new partial result as an Optional.
โ€ข Two other versions
โ€ข One that takes an initial value.
โ€ข One that takes an initial value and BiFunction.
Exercise: Refactor Code
Stream Sources
Stream Sources
JDK 8 Libraries
โ€ข There are 95 methods in 23 classes that return a stream, most are
intermediate operations though.
โ€ข Leaves 71 methods in 15 classes that can be used as practical
sources.
โ€ข There are numerous places to get stream sources.
โ€ข Streams from values
โ€ข Empty streams
โ€ข Streams from functions
โ€ข Streams from arrays
โ€ข Streams from collections
โ€ข Streams from files
โ€ข Streams from other sources
Stream Sources
Collection Interface
โ€ข stream()
โ€ข Provides a sequential stream of elements in the collection.
โ€ข parallelStream()
โ€ข Provides a parallel stream of elements in the collection.
โ€ข Uses the fork-join framework for implementation.
โ€ข Only Collection can provide a parallel stream directly.
Arrays Class
โ€ข stream()
โ€ข Array is a collection of data, so logical to be able to create a
stream.
โ€ข Provides a sequential stream.
โ€ข Overloaded methods for different types, int, double, long, Object
Stream Sources
Some other Classes
โ€ข Files Class: find, list, lines, walk.
โ€ข Random numbers to produce finite or infinite streams
with or without seeds: Random,
ThreadLocalRandom, SplittableRandom.
โ€ข BufferReader, JarFile, ZipFile, Pattern, Charsequence, etc.
Stream Sources
Primitive Streams
โ€ข IntStream, DoubleStream, LongStream are primitive
specialisations of the Stream interface.
โ€ข range(int, int), rangeClosed(int, int)
โ€ข A stream from a start to an end value (exclusive or
inclusive)
โ€ข generate(IntSupplier), iterate(int,
IntUnaryOperator)
โ€ข An infinite stream created by a given Supplier.
โ€ข iterate uses a seed to start the stream.
Optional
Optional
Problems with null
โ€ข Certain situations in Java return a result which is a null, i.e. the
reference to an object isnโ€™t set.
โ€ข It tries to help eliminate NullPointerExceptionโ€™s.
โ€ข Terminal operations like min(), max(), may not return a direct result,
suppose the input stream is empty?
โ€ข Introducing Optional<T>:
โ€ข It is a container for an object reference (null, or real object).
โ€ข It is a stream with either 0 or 1 elements, but never null.
โ€ข Can be used in powerful ways to provide complex conditional handling.
โ€ข Doesnโ€™t stop developers from returning null, but an Optional tells you do
maybe rather check.
โ€ข Was added for the Stream API, but you can also use it.
Optional
Creating an Optional
โ€ข <T> Optional<T> empty(): Returns an empty
Optional.
โ€ข <T> Optional<T> of(T value): Returns an
Optional containing the specified value. If the
specified value is null, it throws a
NullPointerException.
โ€ข <T> Optional<T> ofNullable(T value): Same as
above, but if the specified value is null, it returns and
empty Optional.
Optional
Getting Data from an Optional
โ€ข <T> get(): Returns the value, but will throw
NoSuchElementException is value is empty.
โ€ข <T> orElse(T defaultValue): Returns the default value if value
is empty.
โ€ข <T> orElseGet(Supplier<? Extends T>
defaultSupplier): Same as above, but supplier gets the value.
โ€ข <X extends Throwable> T orElseThrow(Supplier<?
Extends T> exceptionSupplier): If empty throw the
exception from the supplier.
Demo: Refactor to
Optional
Exercise: Optional
Debugging Streams
Debugging Streams
Solution
โ€ข Most IDEโ€™s will support debugging Streams and breakpoints on
streams.
โ€ข As you can pass in the behaviour for each operation via a lambda
you can always add a System.out.println() or logging as part
of the behaviour.
โ€ข If you donโ€™t want to mess around with your current behaviour you
can use the peek operation.
โ€ข The peek(Consumer <? Super T> action) methods was
added for debugging and should only be used for debugging.
โ€ข Each element will pass through it and the action will be applied to
it.
Homework
Homework Exercises
How does it work?
โ€ข The exercises for this month are all small exercises that you will complete
using the things you have learned during this presentation.
โ€ข There are 21 exercises to complete.
โ€ข For first month focus on using lambda expressions, method references and
some of the new methods that have been added to existing classes.
โ€ข There is a template source file that you should use to create the answers to
the exercises called Test.java under exercises package the test folder.
โ€ข To simplify things the lists and maps you need for the exercises have already
been created.
โ€ข You just need to focus on the code to solve the exercise.
โ€ข The solutions are in the Test.java file in the solutions package, but try all the
exercises first before taking a peak.
Books
Books on Lambdas and Streams
Thank you!
Ad

More Related Content

What's hot (20)

Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
Sony India Software Center
ย 
Angular Unit Testing
Angular Unit TestingAngular Unit Testing
Angular Unit Testing
Shailendra Chauhan
ย 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
Nilesh Dalvi
ย 
Exception handling and templates
Exception handling and templatesException handling and templates
Exception handling and templates
farhan amjad
ย 
collection framework in java
collection framework in javacollection framework in java
collection framework in java
MANOJ KUMAR
ย 
Class and object
Class and objectClass and object
Class and object
Prof. Dr. K. Adisesha
ย 
Functional programming
Functional programmingFunctional programming
Functional programming
Lhouceine OUHAMZA
ย 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
Ram132
ย 
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptxUnit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
Malla Reddy University
ย 
Typescript ppt
Typescript pptTypescript ppt
Typescript ppt
akhilsreyas
ย 
input/ output in java
input/ output  in javainput/ output  in java
input/ output in java
sharma230399
ย 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
Michelle Anne Meralpis
ย 
Java Collections API
Java Collections APIJava Collections API
Java Collections API
Alex Miller
ย 
TypeScript Best Practices
TypeScript Best PracticesTypeScript Best Practices
TypeScript Best Practices
felixbillon
ย 
Junit
JunitJunit
Junit
FAROOK Samath
ย 
Introduction to angular with a simple but complete project
Introduction to angular with a simple but complete projectIntroduction to angular with a simple but complete project
Introduction to angular with a simple but complete project
Jadson Santos
ย 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
Scott Leberknight
ย 
Getting started with typescript
Getting started with typescriptGetting started with typescript
Getting started with typescript
C...L, NESPRESSO, WAFAASSURANCE, SOFRECOM ORANGE
ย 
Stack data structure
Stack data structureStack data structure
Stack data structure
Tech_MX
ย 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.
David Gรณmez Garcรญa
ย 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
Nilesh Dalvi
ย 
Exception handling and templates
Exception handling and templatesException handling and templates
Exception handling and templates
farhan amjad
ย 
collection framework in java
collection framework in javacollection framework in java
collection framework in java
MANOJ KUMAR
ย 
Functional programming
Functional programmingFunctional programming
Functional programming
Lhouceine OUHAMZA
ย 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
Ram132
ย 
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptxUnit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
Malla Reddy University
ย 
Typescript ppt
Typescript pptTypescript ppt
Typescript ppt
akhilsreyas
ย 
input/ output in java
input/ output  in javainput/ output  in java
input/ output in java
sharma230399
ย 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
Michelle Anne Meralpis
ย 
Java Collections API
Java Collections APIJava Collections API
Java Collections API
Alex Miller
ย 
TypeScript Best Practices
TypeScript Best PracticesTypeScript Best Practices
TypeScript Best Practices
felixbillon
ย 
Introduction to angular with a simple but complete project
Introduction to angular with a simple but complete projectIntroduction to angular with a simple but complete project
Introduction to angular with a simple but complete project
Jadson Santos
ย 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
Scott Leberknight
ย 
Stack data structure
Stack data structureStack data structure
Stack data structure
Tech_MX
ย 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.
David Gรณmez Garcรญa
ย 

Viewers also liked (12)

Java8 javatime-api
Java8 javatime-apiJava8 javatime-api
Java8 javatime-api
Jini Lee
ย 
Java8
Java8Java8
Java8
fbenault
ย 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional Interfaces
Ganesh Samarthyam
ย 
Java 8 Date and Time API
Java 8 Date and Time APIJava 8 Date and Time API
Java 8 Date and Time API
Ganesh Samarthyam
ย 
java.io - streams and files
java.io - streams and filesjava.io - streams and files
java.io - streams and files
Marcello Thiry
ย 
Eclipse Day India 2015 - Java 8 Overview
Eclipse Day India 2015 - Java 8 OverviewEclipse Day India 2015 - Java 8 Overview
Eclipse Day India 2015 - Java 8 Overview
Eclipse Day India
ย 
Functional Java 8 in everyday life
Functional Java 8 in everyday lifeFunctional Java 8 in everyday life
Functional Java 8 in everyday life
Andrea Iacono
ย 
Major Java 8 features
Major Java 8 featuresMajor Java 8 features
Major Java 8 features
Sanjoy Kumar Roy
ย 
Java8
Java8Java8
Java8
Freeman Zhang
ย 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
Shahjahan Samoon
ย 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
Anton Keks
ย 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
Intelligo Technologies
ย 
Java8 javatime-api
Java8 javatime-apiJava8 javatime-api
Java8 javatime-api
Jini Lee
ย 
Java8
Java8Java8
Java8
fbenault
ย 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional Interfaces
Ganesh Samarthyam
ย 
Java 8 Date and Time API
Java 8 Date and Time APIJava 8 Date and Time API
Java 8 Date and Time API
Ganesh Samarthyam
ย 
java.io - streams and files
java.io - streams and filesjava.io - streams and files
java.io - streams and files
Marcello Thiry
ย 
Eclipse Day India 2015 - Java 8 Overview
Eclipse Day India 2015 - Java 8 OverviewEclipse Day India 2015 - Java 8 Overview
Eclipse Day India 2015 - Java 8 Overview
Eclipse Day India
ย 
Functional Java 8 in everyday life
Functional Java 8 in everyday lifeFunctional Java 8 in everyday life
Functional Java 8 in everyday life
Andrea Iacono
ย 
Major Java 8 features
Major Java 8 featuresMajor Java 8 features
Major Java 8 features
Sanjoy Kumar Roy
ย 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
Shahjahan Samoon
ย 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
Anton Keks
ย 
Ad

Similar to Streams in Java 8 (20)

Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streams
jessitron
ย 
cb streams - gavin pickin
cb streams - gavin pickincb streams - gavin pickin
cb streams - gavin pickin
Ortus Solutions, Corp
ย 
Stream processing from single node to a cluster
Stream processing from single node to a clusterStream processing from single node to a cluster
Stream processing from single node to a cluster
Gal Marder
ย 
A Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its APIA Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its API
Jรถrn Guy SรผรŸ JGS
ย 
CBStreams - Java Streams for ColdFusion (CFML)
CBStreams - Java Streams for ColdFusion (CFML)CBStreams - Java Streams for ColdFusion (CFML)
CBStreams - Java Streams for ColdFusion (CFML)
Ortus Solutions, Corp
ย 
ITB2019 CBStreams : Accelerate your Functional Programming with the power of ...
ITB2019 CBStreams : Accelerate your Functional Programming with the power of ...ITB2019 CBStreams : Accelerate your Functional Programming with the power of ...
ITB2019 CBStreams : Accelerate your Functional Programming with the power of ...
Ortus Solutions, Corp
ย 
2CPP17 - File IO
2CPP17 - File IO2CPP17 - File IO
2CPP17 - File IO
Michael Heron
ย 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project Lambda
Rahman USTA
ย 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
teach4uin
ย 
Java 8
Java 8Java 8
Java 8
Sudipta K Paik
ย 
Java 8 Feature Preview
Java 8 Feature PreviewJava 8 Feature Preview
Java 8 Feature Preview
Jim Bethancourt
ย 
02basics
02basics02basics
02basics
Waheed Warraich
ย 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
Manav Prasad
ย 
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptx
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptxChapter 13_m5JAVANOTESAPPLETS,INPUT.pptx
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptx
noonoboom
ย 
C
CC
C
Jerin John
ย 
My first experience with lambda expressions in java
My first experience with lambda expressions in javaMy first experience with lambda expressions in java
My first experience with lambda expressions in java
Scheidt & Bachmann
ย 
JDK8 Streams
JDK8 StreamsJDK8 Streams
JDK8 Streams
Bansilal Haudakari
ย 
Should i Go there
Should i Go thereShould i Go there
Should i Go there
Shimi Bandiel
ย 
Java 8 streams
Java 8 streams Java 8 streams
Java 8 streams
Srinivasan Raghvan
ย 
CHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptxCHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptx
SadhilAggarwal
ย 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streams
jessitron
ย 
Stream processing from single node to a cluster
Stream processing from single node to a clusterStream processing from single node to a cluster
Stream processing from single node to a cluster
Gal Marder
ย 
A Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its APIA Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its API
Jรถrn Guy SรผรŸ JGS
ย 
CBStreams - Java Streams for ColdFusion (CFML)
CBStreams - Java Streams for ColdFusion (CFML)CBStreams - Java Streams for ColdFusion (CFML)
CBStreams - Java Streams for ColdFusion (CFML)
Ortus Solutions, Corp
ย 
ITB2019 CBStreams : Accelerate your Functional Programming with the power of ...
ITB2019 CBStreams : Accelerate your Functional Programming with the power of ...ITB2019 CBStreams : Accelerate your Functional Programming with the power of ...
ITB2019 CBStreams : Accelerate your Functional Programming with the power of ...
Ortus Solutions, Corp
ย 
2CPP17 - File IO
2CPP17 - File IO2CPP17 - File IO
2CPP17 - File IO
Michael Heron
ย 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project Lambda
Rahman USTA
ย 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
teach4uin
ย 
Java 8 Feature Preview
Java 8 Feature PreviewJava 8 Feature Preview
Java 8 Feature Preview
Jim Bethancourt
ย 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
Manav Prasad
ย 
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptx
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptxChapter 13_m5JAVANOTESAPPLETS,INPUT.pptx
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptx
noonoboom
ย 
My first experience with lambda expressions in java
My first experience with lambda expressions in javaMy first experience with lambda expressions in java
My first experience with lambda expressions in java
Scheidt & Bachmann
ย 
Should i Go there
Should i Go thereShould i Go there
Should i Go there
Shimi Bandiel
ย 
CHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptxCHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptx
SadhilAggarwal
ย 
Ad

More from Tobias Coetzee (6)

Serverless - Applications Running in Their Natural State
Serverless - Applications Running in Their Natural StateServerless - Applications Running in Their Natural State
Serverless - Applications Running in Their Natural State
Tobias Coetzee
ย 
Relationship Counselling with Neo4j
Relationship Counselling with Neo4jRelationship Counselling with Neo4j
Relationship Counselling with Neo4j
Tobias Coetzee
ย 
Swagger: Restful documentation that won't put you to sleep
Swagger: Restful documentation that won't put you to sleepSwagger: Restful documentation that won't put you to sleep
Swagger: Restful documentation that won't put you to sleep
Tobias Coetzee
ย 
Use Neo4j In Your Next Java Project
Use Neo4j In Your Next Java ProjectUse Neo4j In Your Next Java Project
Use Neo4j In Your Next Java Project
Tobias Coetzee
ย 
Lambdas in Java 8
Lambdas in Java 8Lambdas in Java 8
Lambdas in Java 8
Tobias Coetzee
ย 
How to prepare your Enterprise for NoSQL
How to prepare your Enterprise for NoSQLHow to prepare your Enterprise for NoSQL
How to prepare your Enterprise for NoSQL
Tobias Coetzee
ย 
Serverless - Applications Running in Their Natural State
Serverless - Applications Running in Their Natural StateServerless - Applications Running in Their Natural State
Serverless - Applications Running in Their Natural State
Tobias Coetzee
ย 
Relationship Counselling with Neo4j
Relationship Counselling with Neo4jRelationship Counselling with Neo4j
Relationship Counselling with Neo4j
Tobias Coetzee
ย 
Swagger: Restful documentation that won't put you to sleep
Swagger: Restful documentation that won't put you to sleepSwagger: Restful documentation that won't put you to sleep
Swagger: Restful documentation that won't put you to sleep
Tobias Coetzee
ย 
Use Neo4j In Your Next Java Project
Use Neo4j In Your Next Java ProjectUse Neo4j In Your Next Java Project
Use Neo4j In Your Next Java Project
Tobias Coetzee
ย 
Lambdas in Java 8
Lambdas in Java 8Lambdas in Java 8
Lambdas in Java 8
Tobias Coetzee
ย 
How to prepare your Enterprise for NoSQL
How to prepare your Enterprise for NoSQLHow to prepare your Enterprise for NoSQL
How to prepare your Enterprise for NoSQL
Tobias Coetzee
ย 

Recently uploaded (20)

Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
ย 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
ย 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
ย 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
ย 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
ย 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
ย 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
ย 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
ย 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
ย 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
ย 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
ย 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
ย 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
ย 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
ย 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
ย 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
ย 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
ย 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
ย 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
ย 
AI Changes Everything โ€“ Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything โ€“ Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything โ€“ Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything โ€“ Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
ย 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
ย 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
ย 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
ย 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
ย 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
ย 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
ย 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
ย 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
ย 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
ย 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
ย 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
ย 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
ย 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
ย 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
ย 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
ย 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
ย 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
ย 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
ย 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
ย 
AI Changes Everything โ€“ Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything โ€“ Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything โ€“ Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything โ€“ Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
ย 

Streams in Java 8

  • 1. Streams in Java 8 Start programming in a more functional style
  • 2. Background Who am I? โ€ข Tobias Coetzee โ€ข Iโ€™m a Technical Lead at BBD โ€ข I present the Java Expert Level Certifications at BBD (EJB, JPA, etc.) โ€ข Iโ€™m currently a banker โ€ข Part of the JoziJug organising committee โ€ข I like to run โ€ข This partially presentation is based on a Simon Ritter course โ€ข @tobiascode โ€ข https://github.com/Jozi-JUG/streamtraining
  • 3. Outcomes What are the take awayโ€™s? โ€ข Know the differences between functional and imperative programming โ€ข Be able to define the elements of a stream โ€ข Use intermediate and terminal operations โ€ข Create streams from different data types โ€ข Avoid NullPointerExceptions with the Optional Class โ€ข Debug streams
  • 4. What Did We Do Last Time?
  • 5. Lambdas Summary โ€ข CPUโ€™s are getting much faster, but we are getting more cores to use. โ€ข Inject functionality into methods, the same way we inject values into methods. โ€ข Lambda syntax and rules, (parameters) -> {lambda body} โ€ข Functional interfaces are interfaces that have only one abstract method. โ€ข Lambdas can be used where the type is a functional interface. โ€ข Use lambdas as method parameters or assign them to variables. โ€ข The java.util.function package already gives us a few functional interfaces out of the box. โ€ข Method and constructor references as short hands notation, ::. โ€ข There are a few new methods that can use lambdas in Java 8, e.g. forEach(Consumer c).
  • 8. Functional Programming Imperative โ€ข Values associated with names can be changed, i.e. mutable state. โ€ข The order of execution is defined as a contract. โ€ข Repetition is external and explicit, we are responsible for the โ€œhowโ€. Functional (Declarative) โ€ข Values associated with names are set once and cannot be changed, i.e. immutable state. โ€ข Order of execution is not defined โ€ข Repetition is through the use of recursion or internal repetition, the โ€œhowโ€ is hidden away. Thinking about a problem in terms of immutable values and functions that translate between them.
  • 9. โ€œMultithreaded programming, requiring synchronised access to shared, mutable state, is the assembly language of concurrencyโ€
  • 10. The Elements of a Stream
  • 11. Elements of a Stream What are streams? โ€ข Streams give us functional blocks to better process collections of data with, monads. โ€ข We can chain these blocks together to process collections of data. โ€ข Streams arenโ€™t another data structure. โ€ข Streams can process an infinite list of data. โ€ข Streams use internal iteration meaning we donโ€™t have to code external iteration, the โ€œhowโ€. โ€ข Streams support functional programming as suppose to imperative programming.
  • 12. โ€œThe purpose of streams isnโ€™t just to convert from one collection to another; itโ€™s to be able to provide a common set of operations over dataโ€
  • 13. Elements of a Stream Structure of a Stream โ€ข A stream consists of 3 types of things 1. A source 2. Zero or more intermediate operations 3. A terminal operation result = albums.stream() .filter(track -> track.getLength() > 300) .map(Track::getName) .collect(Collectors.toSet()); Source Intermediate Operation Intermediate Operation Terminal Operation Result
  • 15. Elements of a Stream How they work โ€ข The pipeline is only evaluated when the terminal operation is called. โ€ข The terminal operations pulls the data, the source doesnโ€™t push it. โ€ข Uses the stream characteristics to help identify optimisations. โ€ข This allows intermediate operations to be merged: โ€ข Avoiding multiple redundant passes on data โ€ข Short-circuit operations โ€ข Laze evaluation โ€ข The stream takes care of the โ€œhowโ€.
  • 17. Intermediate Operations Intermediate โ€ข A stream provides a sequence of elements. โ€ข Supports either sequential or parallel aggregate operations. โ€ข Most operations take a parameter that describes its behaviour, the โ€œwhatโ€. โ€ข Typically using lambda expressions. โ€ข Must be non-interfering โ€ข Stateless โ€ข Streams can switch between sequential and parallel, but all processing is either done sequential or parallel, last call wins.
  • 18. Intermediate Operations Filtering and Mapping Interface Description filter(Predicate) Returns a stream with only those elements that return true for the Predicate map(Function) Return a stream where the given Function is applied to each element on the input stream mapToInt, mapToDouble, mapToLong Like map(), but producing streams of primitives rather than objects. distinct() Returns a stream with no duplicate elements
  • 19. Intermediate Operations Map() and FlatMap() โ€ข Map values from a stream either as one-to-one or one- to-many, but still only produce one stream. map() input stream output stream one-to-one flatMap() input stream output stream one-to-many
  • 20. Intermediate Operations Sizing and Sorting Interface Description skip(long) Returns a stream that skips the first n elements of the input stream limit(long) Return a stream that only contains the first n elements of the input stream sorted(Comparator) Returns a stream that is sorted with the order determined by the Comparator. With no arguments sorts by natural order. unordered() Returns a stream that is unordered (used internally). Can improve efficiency of operations like distinct() and groupingBy()
  • 22. Terminal Operations Terminal โ€ข Terminates the pipeline of the operations on the stream. โ€ข Only at this point is any processing performed. โ€ข This allows for optimisation of the pipeline: โ€ข Lazy evaluation โ€ข Merged/fused operations โ€ข Elimination of redundant operations โ€ข Parallel execution โ€ข Generates an explicit result of a side effect.
  • 23. Intermediate Operations Matching Elements and Iteration Interface Description findFirst(Predicate) The first element that matches predicate findAny(Predicate) Like findFirst(), but for a parallel stream allMatch(Predicate) All elements in the stream match predicate anyMatch(Predicate) Any element in the stream matches predicate noneMatch(Predicate) No elements match the predicate forEach(Consumer) Performs an action on each element forEachOrdered(Consumer) Like above, but ensures order is respected when used for parallel stream * * * Encourages non-functional programming style
  • 24. Intermediate Operations Collecting Results and Numerical Results Interface Description collect(Collector) Performs a mutable reduction on a stream toArray() Returns an array containing the elements of the stream count() Returns how many elements are in the stream max(Comparator) The maximum value element of the stream, returns an Optional min(Comparator) The minimum value element of the stream, returns an Optional average() Return the arithmetic mean of the stream, returns an Optional sum() Returns the sum of the stream elements * There are a lot of built-in Collectors *
  • 25. Terminal Operations Creating a Single Result โ€ข The collect function isnโ€™t the only option. โ€ข reduce(BinaryOperator accumulator) โ€ข Also called folding in FP. โ€ข Performs a reduction on the stream using the BinaryOperator. โ€ข The accumulator takes a partial result and the next element and returns a new partial result as an Optional. โ€ข Two other versions โ€ข One that takes an initial value. โ€ข One that takes an initial value and BiFunction.
  • 28. Stream Sources JDK 8 Libraries โ€ข There are 95 methods in 23 classes that return a stream, most are intermediate operations though. โ€ข Leaves 71 methods in 15 classes that can be used as practical sources. โ€ข There are numerous places to get stream sources. โ€ข Streams from values โ€ข Empty streams โ€ข Streams from functions โ€ข Streams from arrays โ€ข Streams from collections โ€ข Streams from files โ€ข Streams from other sources
  • 29. Stream Sources Collection Interface โ€ข stream() โ€ข Provides a sequential stream of elements in the collection. โ€ข parallelStream() โ€ข Provides a parallel stream of elements in the collection. โ€ข Uses the fork-join framework for implementation. โ€ข Only Collection can provide a parallel stream directly. Arrays Class โ€ข stream() โ€ข Array is a collection of data, so logical to be able to create a stream. โ€ข Provides a sequential stream. โ€ข Overloaded methods for different types, int, double, long, Object
  • 30. Stream Sources Some other Classes โ€ข Files Class: find, list, lines, walk. โ€ข Random numbers to produce finite or infinite streams with or without seeds: Random, ThreadLocalRandom, SplittableRandom. โ€ข BufferReader, JarFile, ZipFile, Pattern, Charsequence, etc.
  • 31. Stream Sources Primitive Streams โ€ข IntStream, DoubleStream, LongStream are primitive specialisations of the Stream interface. โ€ข range(int, int), rangeClosed(int, int) โ€ข A stream from a start to an end value (exclusive or inclusive) โ€ข generate(IntSupplier), iterate(int, IntUnaryOperator) โ€ข An infinite stream created by a given Supplier. โ€ข iterate uses a seed to start the stream.
  • 33. Optional Problems with null โ€ข Certain situations in Java return a result which is a null, i.e. the reference to an object isnโ€™t set. โ€ข It tries to help eliminate NullPointerExceptionโ€™s. โ€ข Terminal operations like min(), max(), may not return a direct result, suppose the input stream is empty? โ€ข Introducing Optional<T>: โ€ข It is a container for an object reference (null, or real object). โ€ข It is a stream with either 0 or 1 elements, but never null. โ€ข Can be used in powerful ways to provide complex conditional handling. โ€ข Doesnโ€™t stop developers from returning null, but an Optional tells you do maybe rather check. โ€ข Was added for the Stream API, but you can also use it.
  • 34. Optional Creating an Optional โ€ข <T> Optional<T> empty(): Returns an empty Optional. โ€ข <T> Optional<T> of(T value): Returns an Optional containing the specified value. If the specified value is null, it throws a NullPointerException. โ€ข <T> Optional<T> ofNullable(T value): Same as above, but if the specified value is null, it returns and empty Optional.
  • 35. Optional Getting Data from an Optional โ€ข <T> get(): Returns the value, but will throw NoSuchElementException is value is empty. โ€ข <T> orElse(T defaultValue): Returns the default value if value is empty. โ€ข <T> orElseGet(Supplier<? Extends T> defaultSupplier): Same as above, but supplier gets the value. โ€ข <X extends Throwable> T orElseThrow(Supplier<? Extends T> exceptionSupplier): If empty throw the exception from the supplier.
  • 39. Debugging Streams Solution โ€ข Most IDEโ€™s will support debugging Streams and breakpoints on streams. โ€ข As you can pass in the behaviour for each operation via a lambda you can always add a System.out.println() or logging as part of the behaviour. โ€ข If you donโ€™t want to mess around with your current behaviour you can use the peek operation. โ€ข The peek(Consumer <? Super T> action) methods was added for debugging and should only be used for debugging. โ€ข Each element will pass through it and the action will be applied to it.
  • 41. Homework Exercises How does it work? โ€ข The exercises for this month are all small exercises that you will complete using the things you have learned during this presentation. โ€ข There are 21 exercises to complete. โ€ข For first month focus on using lambda expressions, method references and some of the new methods that have been added to existing classes. โ€ข There is a template source file that you should use to create the answers to the exercises called Test.java under exercises package the test folder. โ€ข To simplify things the lists and maps you need for the exercises have already been created. โ€ข You just need to focus on the code to solve the exercise. โ€ข The solutions are in the Test.java file in the solutions package, but try all the exercises first before taking a peak.
  • 42. Books
  • 43. Books on Lambdas and Streams