SlideShare una empresa de Scribd logo
1 de 44
Descargar para leer sin conexión
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!

Más contenido relacionado

La actualidad más candente

Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2José Paumard
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentationguest11106b
 
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
 
Java Collections
Java CollectionsJava Collections
Java Collectionsparag
 
Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsJava 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsNewCircle Training
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - JavaDrishti Bhalla
 
Lambda Expressions in Java
Lambda Expressions in JavaLambda Expressions in Java
Lambda Expressions in JavaErhan Bagdemir
 
java 8 new features
java 8 new features java 8 new features
java 8 new features Rohit Verma
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in javaCPD INDIA
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8Martin Toshev
 
Java collections concept
Java collections conceptJava collections concept
Java collections conceptkumar gaurav
 
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Edureka!
 

La actualidad más candente (20)

Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
 
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.
 
Java Collections
Java CollectionsJava Collections
Java Collections
 
Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsJava 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & Streams
 
Introduction to java 8 stream api
Introduction to java 8 stream apiIntroduction to java 8 stream api
Introduction to java 8 stream api
 
Java8 features
Java8 featuresJava8 features
Java8 features
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
 
Lambda Expressions in Java
Lambda Expressions in JavaLambda Expressions in Java
Lambda Expressions in Java
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
 
Java 8 streams
Java 8 streamsJava 8 streams
Java 8 streams
 
java 8 new features
java 8 new features java 8 new features
java 8 new features
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
 
JPA and Hibernate
JPA and HibernateJPA and Hibernate
JPA and Hibernate
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
 
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
 

Destacado

Java8 javatime-api
Java8 javatime-apiJava8 javatime-api
Java8 javatime-apiJini Lee
 
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 InterfacesGanesh Samarthyam
 
java.io - streams and files
java.io - streams and filesjava.io - streams and files
java.io - streams and filesMarcello 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 OverviewEclipse Day India
 
Functional Java 8 in everyday life
Functional Java 8 in everyday lifeFunctional Java 8 in everyday life
Functional Java 8 in everyday lifeAndrea Iacono
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streamsShahjahan 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 StreamsAnton Keks
 

Destacado (11)

Java8 javatime-api
Java8 javatime-apiJava8 javatime-api
Java8 javatime-api
 
Java8
Java8Java8
Java8
 
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
 
Java 8 Date and Time API
Java 8 Date and Time APIJava 8 Date and Time API
Java 8 Date and Time API
 
java.io - streams and files
java.io - streams and filesjava.io - streams and files
java.io - streams and files
 
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
 
Functional Java 8 in everyday life
Functional Java 8 in everyday lifeFunctional Java 8 in everyday life
Functional Java 8 in everyday life
 
Java8
Java8Java8
Java8
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
 
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
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
 

Similar a Streams in Java 8

Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streamsjessitron
 
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 clusterGal 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 APIJö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
 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project LambdaRahman USTA
 
L21 io streams
L21 io streamsL21 io streams
L21 io streamsteach4uin
 
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptx
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptxChapter 13_m5JAVANOTESAPPLETS,INPUT.pptx
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptxnoonoboom
 
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 javaScheidt & Bachmann
 
CHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptxCHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptxSadhilAggarwal
 
Performance van Java 8 en verder - Jeroen Borgers
Performance van Java 8 en verder - Jeroen BorgersPerformance van Java 8 en verder - Jeroen Borgers
Performance van Java 8 en verder - Jeroen BorgersNLJUG
 

Similar a Streams in Java 8 (20)

Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streams
 
cb streams - gavin pickin
cb streams - gavin pickincb streams - gavin pickin
cb streams - gavin pickin
 
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
 
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
 
CBStreams - Java Streams for ColdFusion (CFML)
CBStreams - Java Streams for ColdFusion (CFML)CBStreams - Java Streams for ColdFusion (CFML)
CBStreams - Java Streams for ColdFusion (CFML)
 
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 ...
 
2CPP17 - File IO
2CPP17 - File IO2CPP17 - File IO
2CPP17 - File IO
 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project Lambda
 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
 
Java 8
Java 8Java 8
Java 8
 
Java 8 Feature Preview
Java 8 Feature PreviewJava 8 Feature Preview
Java 8 Feature Preview
 
02basics
02basics02basics
02basics
 
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptx
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptxChapter 13_m5JAVANOTESAPPLETS,INPUT.pptx
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptx
 
C
CC
C
 
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
 
JDK8 Streams
JDK8 StreamsJDK8 Streams
JDK8 Streams
 
Should i Go there
Should i Go thereShould i Go there
Should i Go there
 
Java 8 streams
Java 8 streams Java 8 streams
Java 8 streams
 
CHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptxCHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptx
 
Performance van Java 8 en verder - Jeroen Borgers
Performance van Java 8 en verder - Jeroen BorgersPerformance van Java 8 en verder - Jeroen Borgers
Performance van Java 8 en verder - Jeroen Borgers
 

Más de 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 StateTobias Coetzee
 
Relationship Counselling with Neo4j
Relationship Counselling with Neo4jRelationship Counselling with Neo4j
Relationship Counselling with Neo4jTobias 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 sleepTobias 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 ProjectTobias 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 NoSQLTobias Coetzee
 

Más de 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
 
Relationship Counselling with Neo4j
Relationship Counselling with Neo4jRelationship Counselling with Neo4j
Relationship Counselling with Neo4j
 
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
 
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
 
Lambdas in Java 8
Lambdas in Java 8Lambdas in Java 8
Lambdas in Java 8
 
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
 

Último

08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 

Último (20)

08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 

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