SlideShare a Scribd company logo
An Introduction to Streams
Manvendra Singh
@Manvendra_SK
Java 8
() -> Agenda
What is a Stream?
Creating Streams.
Optional Values.
Operations on Streams.
Collecting data using Collectors.
Get code at...
git clone
git@github.com:manvendrasinghkadam/ja
va8streams.git
1. What is a Stream?
An aggregate operation computes a single
value from a collection of values. Result may be
primitive value, void or an object which can be
a Person, List or Map!
A stream is a sequence of data elements
supporting sequential and parallel aggregate
operations.
Steams are not collections. Streams focus on
aggregate computations on data elements from
a data source that is typically, but not
necessarily, collections!
... No storage
A collection is an in-memory data structure that
stores all its elements. Whereas stream has no
storage; it does not store elements.
A stream pulls elements from a data source on-
demand and passes them to a pipeline of
operations for processing.
... Infinite Streams
A collection cannot represent a group of infinite
elements whereas a stream can.
A stream pulls its elements from a data source
that can be a collection, a function that
generates data, an I/O channel, etc.
Because a function can generate an infinite
number of elements, it is possible to have a
stream representing a sequence of infinite data
elements!
... Imperative vs. Functional
Collections support imperative programming
whereas streams support declarative
programming.
When we use collections, we need to know
what we want and how to get it; this is the
feature of imperative programming. When we
use streams, we specify only what we want in
terms of stream operations; the how part is
taken care by the Streams API.
When we use Streams, we specify what
operations we want to perform on its elements
using the built-in methods provided by the
Streams API, typically by passing a lambda
... Stream Operations
A Stream support 2 types of operations.
Intermediate operations (Lazy operations).
Terminal operations (Eager operations).
Operations are known as lazy and eager
based on the way they pull the data
elements from the data source.
A lazy operation on a stream does not
process the elements of the stream until
another eager operation is called on the
stream.
Example is here...
... Stream Operations (cont...)
1, 2,
3, 4,
5
filter map reduce1, 2, 3, 4, 5 1, 3, 5 1, 9, 25 35
numbers.stream().filter(x -> x % 2 == 1).map(x -> x * x).reduce(0, (x, y) -> x + y);
... Streams are not reusable
Unlike collections, Streams are not reusable. They
are one-shot objects.
A Stream cannot be reused after calling a terminal
operation on it.
A Stream implementation may throw an
IllegalStateException if it detects that the
stream is being reused.
Example is here...
... Example explained
2. Creating Streams
There are many ways to create streams. Many
existing classes in the Java libraries have received
new methods that return a stream. Based on the
data source, stream creation can be categorized as
follows:
Streams from values
Empty streams
Streams from Functions
Streams from Arrays
Streams from Collections
Streams from Files
... Streams from values
The Stream interface contains two of() overloaded
methods to create a sequential Stream from a
single value and multiple values.
Example is here...
... Empty Streams
An empty stream is a stream with no elements.
The Stream interface contains an empty() static
method to create an empty sequential stream.
Example is here...
... Streams from Functions
An infinite stream is a stream with a data source
capable of generating infinite number of elements.
The Stream interface contains the two static
methods to generate an infinite stream:
generate: Generates sequential unordered stream.
iterate: Generates sequential ordered stream.
Example is here...
... Streams from Arrays
The Arrays class in the java.util package contains an
overloaded stream() static method to create
sequential streams from arrays.
Example is here...
... Streams from Collections
The Collection interface contains the stream()
method that create sequential stream.
Example is here...
... Streams from Files
Java 8 has added many methods to the classes in
the java.io and java.nio.file packages to support
I/O operations using Streams.
Example is here...
3. Optional Values
null is used to represent nothing or an empty result.
Most often, a method returns null if it does not have a
result to return. This has been a source of frequent
NullPointerException in Java programs.
Java 8 has introduced an Optional<T> class in
the java.util package to deal with
NullPointerException gracefully. Methods that
may return nothing should return an Optional
instead of null.
Actually there is no solution for this
NullPointerException. As Optional is the
wrapper around null, it throws a
NoSuchElementException if the value it
contains is null.
4. Operations on Streams
Here is a list of commonly used Stream operations.
distinct – Intermediate
filter – Intermediate
limit – Intermediate
map – Intermediate
peek – Intermediate
skip – Intermediate
sorted – Intermediate
4. Operations on Streams (cont...)
List is continued here...
allMatch – Terminal
anyMatch – Terminal
findAny – Terminal
findFirst – Terminal
noneMatch – Terminal
forEach – Terminal
reduce – Terminal
... Debugging Stream Pipeline
Sometimes we may want to inspect individual
elements that we get after certain Stream
operation. To do this we Streams API provides us
with the peek operation.
Example is here...
... Iteration using Streams
We can iterate the stream using the forEach
operation.
Example is here...
... Mapping the Stream elements
A map operation applies a function to each
element of the input stream to produce another
output stream. The number of elements in the
input and output streams is the same. The
operation does not modify the elements of the
input stream.
Example is here...
... Filtering the Stream elements
The filter operation is applied on an input stream
to produce another stream, which is known as the
filtered stream. The returned stream by filter
operation is a subset of the input stream.
Example is here...
... Reducing the Stream elements
The reduce operation combines all elements of a
stream to produce a single value by applying a
combining function repeatedly. It is also called
reduction operation or a fold.
Computing the sum, maximum, average, count,
etc. of elements of a stream of integers are
examples of the reduce operation.
Streams API Provides us some specialized methods
for reduce operation on Integers, Doubles and
Floats..
Example is here...
5. Collecting data using Collectors.
There are several cases in which we want to
collect the results of executing a stream
pipeline into a collection such as a List, a Set,
a Map, etc. Sometimes we may want to apply
complex logic to summarize the stream’s data.
This is possible using the collect method.
Example is here...
?
For joining in...
Thanks

More Related Content

What's hot (20)

PDF
Java 8 Stream API. A different way to process collections.
David Gómez García
 
PPTX
Java 8 Lambda and Streams
Venkata Naga Ravi
 
PDF
Java 8 Lambda Expressions & Streams
NewCircle Training
 
PPTX
Introduction to java 8 stream api
Vladislav sidlyarevich
 
PPTX
Understanding java streams
Shahjahan Samoon
 
PPTX
Java Lambda Expressions.pptx
SameerAhmed593310
 
PDF
Streams in Java 8
Tobias Coetzee
 
PDF
Generics
Ravi_Kant_Sahu
 
PPT
Java Input Output and File Handling
Sunil OS
 
PPTX
String in java
Ideal Eyes Business College
 
PDF
Lambda Expressions in Java
Erhan Bagdemir
 
PPTX
for loop in java
Majid Ali
 
PPTX
Java 8 - Features Overview
Sergii Stets
 
PPTX
Type casting in java
Farooq Baloch
 
ODP
Introduction to Java 8
Knoldus Inc.
 
PPTX
Functional programming with Java 8
LivePerson
 
PPT
Generics in java
suraj pandey
 
PPTX
Typescript ppt
akhilsreyas
 
PPT
Strings
naslin prestilda
 
PDF
JavaScript - Chapter 10 - Strings and Arrays
WebStackAcademy
 
Java 8 Stream API. A different way to process collections.
David Gómez García
 
Java 8 Lambda and Streams
Venkata Naga Ravi
 
Java 8 Lambda Expressions & Streams
NewCircle Training
 
Introduction to java 8 stream api
Vladislav sidlyarevich
 
Understanding java streams
Shahjahan Samoon
 
Java Lambda Expressions.pptx
SameerAhmed593310
 
Streams in Java 8
Tobias Coetzee
 
Generics
Ravi_Kant_Sahu
 
Java Input Output and File Handling
Sunil OS
 
Lambda Expressions in Java
Erhan Bagdemir
 
for loop in java
Majid Ali
 
Java 8 - Features Overview
Sergii Stets
 
Type casting in java
Farooq Baloch
 
Introduction to Java 8
Knoldus Inc.
 
Functional programming with Java 8
LivePerson
 
Generics in java
suraj pandey
 
Typescript ppt
akhilsreyas
 
JavaScript - Chapter 10 - Strings and Arrays
WebStackAcademy
 

Viewers also liked (9)

PPTX
Lambda Expressions in Java 8
icarter09
 
PDF
Java SE 9 modules (JPMS) - an introduction
Stephen Colebourne
 
PDF
Java 9, JShell, and Modularity
Mohammad Hossein Rimaz
 
PDF
Working With Concurrency In Java 8
Heartin Jacob
 
PDF
Java9 Beyond Modularity - Java 9 más allá de la modularidad
David Gómez García
 
PPTX
Java 9 Modules: The Duke Yet Lives That OSGi Shall Depose
Nikita Lipsky
 
PDF
Parallel streams in java 8
David Gómez García
 
PPTX
The do's and don'ts with java 9 (Devoxx 2017)
Robert Scholte
 
PDF
Real World Java 9
Trisha Gee
 
Lambda Expressions in Java 8
icarter09
 
Java SE 9 modules (JPMS) - an introduction
Stephen Colebourne
 
Java 9, JShell, and Modularity
Mohammad Hossein Rimaz
 
Working With Concurrency In Java 8
Heartin Jacob
 
Java9 Beyond Modularity - Java 9 más allá de la modularidad
David Gómez García
 
Java 9 Modules: The Duke Yet Lives That OSGi Shall Depose
Nikita Lipsky
 
Parallel streams in java 8
David Gómez García
 
The do's and don'ts with java 9 (Devoxx 2017)
Robert Scholte
 
Real World Java 9
Trisha Gee
 
Ad

Similar to Java 8 Streams (20)

PPTX
Java Advanced Topic - Streams Presentations
MuraliD32
 
PDF
Functional programming with streams
Riadh MNASRI
 
PDF
Java Lambda internals with invoke dynamic
Mohit Kumar
 
PDF
Charles Sharp: Java 8 Streams
jessitron
 
PPTX
Java 8 Streams And Common Operations By Harmeet Singh(Taara)
Harmeet Singh(Taara)
 
PDF
Lambda.pdf
ManishWalia18
 
PPTX
JDK8 Streams
Bansilal Haudakari
 
PDF
Harnessing the Power of Java 8 Streams
IndicThreads
 
PDF
Java 8 Streams - in Depth
Haim Michael
 
PDF
Going reactive in java
José Paumard
 
PPTX
Java 8 streams
Manav Prasad
 
PPTX
Java se 8 streams pt1
Lars Lemos
 
PDF
cb streams - gavin pickin
Ortus Solutions, Corp
 
PDF
Concept of Stream API Java 1.8
InnovationM
 
PDF
CBStreams - Java Streams for ColdFusion (CFML)
Ortus Solutions, Corp
 
PDF
ITB2019 CBStreams : Accelerate your Functional Programming with the power of ...
Ortus Solutions, Corp
 
PPTX
A Brief Conceptual Introduction to Functional Java 8 and its API
Jörn Guy Süß JGS
 
PPTX
ADT02 - Java 8 Lambdas and the Streaming API
Michael Remijan
 
PDF
Collectors in the Wild
José Paumard
 
PDF
Java 8 Stream API (Valdas Zigas)
Kaunas Java User Group
 
Java Advanced Topic - Streams Presentations
MuraliD32
 
Functional programming with streams
Riadh MNASRI
 
Java Lambda internals with invoke dynamic
Mohit Kumar
 
Charles Sharp: Java 8 Streams
jessitron
 
Java 8 Streams And Common Operations By Harmeet Singh(Taara)
Harmeet Singh(Taara)
 
Lambda.pdf
ManishWalia18
 
JDK8 Streams
Bansilal Haudakari
 
Harnessing the Power of Java 8 Streams
IndicThreads
 
Java 8 Streams - in Depth
Haim Michael
 
Going reactive in java
José Paumard
 
Java 8 streams
Manav Prasad
 
Java se 8 streams pt1
Lars Lemos
 
cb streams - gavin pickin
Ortus Solutions, Corp
 
Concept of Stream API Java 1.8
InnovationM
 
CBStreams - Java Streams for ColdFusion (CFML)
Ortus Solutions, Corp
 
ITB2019 CBStreams : Accelerate your Functional Programming with the power of ...
Ortus Solutions, Corp
 
A Brief Conceptual Introduction to Functional Java 8 and its API
Jörn Guy Süß JGS
 
ADT02 - Java 8 Lambdas and the Streaming API
Michael Remijan
 
Collectors in the Wild
José Paumard
 
Java 8 Stream API (Valdas Zigas)
Kaunas Java User Group
 
Ad

Recently uploaded (20)

PDF
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
PPTX
Revolutionizing Code Modernization with AI
KrzysztofKkol1
 
PDF
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
PPTX
Platform for Enterprise Solution - Java EE5
abhishekoza1981
 
PDF
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
PPTX
Java Native Memory Leaks: The Hidden Villain Behind JVM Performance Issues
Tier1 app
 
PPTX
Fundamentals_of_Microservices_Architecture.pptx
MuhammadUzair504018
 
PDF
Streamline Contractor Lifecycle- TECH EHS Solution
TECH EHS Solution
 
PPTX
A Complete Guide to Salesforce SMS Integrations Build Scalable Messaging With...
360 SMS APP
 
PDF
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
PPTX
Comprehensive Guide: Shoviv Exchange to Office 365 Migration Tool 2025
Shoviv Software
 
PDF
GetOnCRM Speeds Up Agentforce 3 Deployment for Enterprise AI Wins.pdf
GetOnCRM Solutions
 
PDF
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
PPTX
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
 
PDF
Powering GIS with FME and VertiGIS - Peak of Data & AI 2025
Safe Software
 
PDF
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
PPTX
How Apagen Empowered an EPC Company with Engineering ERP Software
SatishKumar2651
 
PPTX
Tally software_Introduction_Presentation
AditiBansal54083
 
PPTX
The Role of a PHP Development Company in Modern Web Development
SEO Company for School in Delhi NCR
 
PDF
Salesforce CRM Services.VALiNTRY360
VALiNTRY360
 
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
Revolutionizing Code Modernization with AI
KrzysztofKkol1
 
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
Platform for Enterprise Solution - Java EE5
abhishekoza1981
 
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
Java Native Memory Leaks: The Hidden Villain Behind JVM Performance Issues
Tier1 app
 
Fundamentals_of_Microservices_Architecture.pptx
MuhammadUzair504018
 
Streamline Contractor Lifecycle- TECH EHS Solution
TECH EHS Solution
 
A Complete Guide to Salesforce SMS Integrations Build Scalable Messaging With...
360 SMS APP
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
Comprehensive Guide: Shoviv Exchange to Office 365 Migration Tool 2025
Shoviv Software
 
GetOnCRM Speeds Up Agentforce 3 Deployment for Enterprise AI Wins.pdf
GetOnCRM Solutions
 
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
 
Powering GIS with FME and VertiGIS - Peak of Data & AI 2025
Safe Software
 
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
How Apagen Empowered an EPC Company with Engineering ERP Software
SatishKumar2651
 
Tally software_Introduction_Presentation
AditiBansal54083
 
The Role of a PHP Development Company in Modern Web Development
SEO Company for School in Delhi NCR
 
Salesforce CRM Services.VALiNTRY360
VALiNTRY360
 

Java 8 Streams

  • 1. An Introduction to Streams Manvendra Singh @Manvendra_SK Java 8
  • 2. () -> Agenda What is a Stream? Creating Streams. Optional Values. Operations on Streams. Collecting data using Collectors.
  • 3. Get code at... git clone [email protected]:manvendrasinghkadam/ja va8streams.git
  • 4. 1. What is a Stream? An aggregate operation computes a single value from a collection of values. Result may be primitive value, void or an object which can be a Person, List or Map! A stream is a sequence of data elements supporting sequential and parallel aggregate operations. Steams are not collections. Streams focus on aggregate computations on data elements from a data source that is typically, but not necessarily, collections!
  • 5. ... No storage A collection is an in-memory data structure that stores all its elements. Whereas stream has no storage; it does not store elements. A stream pulls elements from a data source on- demand and passes them to a pipeline of operations for processing.
  • 6. ... Infinite Streams A collection cannot represent a group of infinite elements whereas a stream can. A stream pulls its elements from a data source that can be a collection, a function that generates data, an I/O channel, etc. Because a function can generate an infinite number of elements, it is possible to have a stream representing a sequence of infinite data elements!
  • 7. ... Imperative vs. Functional Collections support imperative programming whereas streams support declarative programming. When we use collections, we need to know what we want and how to get it; this is the feature of imperative programming. When we use streams, we specify only what we want in terms of stream operations; the how part is taken care by the Streams API. When we use Streams, we specify what operations we want to perform on its elements using the built-in methods provided by the Streams API, typically by passing a lambda
  • 8. ... Stream Operations A Stream support 2 types of operations. Intermediate operations (Lazy operations). Terminal operations (Eager operations). Operations are known as lazy and eager based on the way they pull the data elements from the data source. A lazy operation on a stream does not process the elements of the stream until another eager operation is called on the stream. Example is here...
  • 9. ... Stream Operations (cont...) 1, 2, 3, 4, 5 filter map reduce1, 2, 3, 4, 5 1, 3, 5 1, 9, 25 35 numbers.stream().filter(x -> x % 2 == 1).map(x -> x * x).reduce(0, (x, y) -> x + y);
  • 10. ... Streams are not reusable Unlike collections, Streams are not reusable. They are one-shot objects. A Stream cannot be reused after calling a terminal operation on it. A Stream implementation may throw an IllegalStateException if it detects that the stream is being reused. Example is here...
  • 12. 2. Creating Streams There are many ways to create streams. Many existing classes in the Java libraries have received new methods that return a stream. Based on the data source, stream creation can be categorized as follows: Streams from values Empty streams Streams from Functions Streams from Arrays Streams from Collections Streams from Files
  • 13. ... Streams from values The Stream interface contains two of() overloaded methods to create a sequential Stream from a single value and multiple values. Example is here...
  • 14. ... Empty Streams An empty stream is a stream with no elements. The Stream interface contains an empty() static method to create an empty sequential stream. Example is here...
  • 15. ... Streams from Functions An infinite stream is a stream with a data source capable of generating infinite number of elements. The Stream interface contains the two static methods to generate an infinite stream: generate: Generates sequential unordered stream. iterate: Generates sequential ordered stream. Example is here...
  • 16. ... Streams from Arrays The Arrays class in the java.util package contains an overloaded stream() static method to create sequential streams from arrays. Example is here...
  • 17. ... Streams from Collections The Collection interface contains the stream() method that create sequential stream. Example is here...
  • 18. ... Streams from Files Java 8 has added many methods to the classes in the java.io and java.nio.file packages to support I/O operations using Streams. Example is here...
  • 19. 3. Optional Values null is used to represent nothing or an empty result. Most often, a method returns null if it does not have a result to return. This has been a source of frequent NullPointerException in Java programs. Java 8 has introduced an Optional<T> class in the java.util package to deal with NullPointerException gracefully. Methods that may return nothing should return an Optional instead of null. Actually there is no solution for this NullPointerException. As Optional is the wrapper around null, it throws a NoSuchElementException if the value it contains is null.
  • 20. 4. Operations on Streams Here is a list of commonly used Stream operations. distinct – Intermediate filter – Intermediate limit – Intermediate map – Intermediate peek – Intermediate skip – Intermediate sorted – Intermediate
  • 21. 4. Operations on Streams (cont...) List is continued here... allMatch – Terminal anyMatch – Terminal findAny – Terminal findFirst – Terminal noneMatch – Terminal forEach – Terminal reduce – Terminal
  • 22. ... Debugging Stream Pipeline Sometimes we may want to inspect individual elements that we get after certain Stream operation. To do this we Streams API provides us with the peek operation. Example is here...
  • 23. ... Iteration using Streams We can iterate the stream using the forEach operation. Example is here...
  • 24. ... Mapping the Stream elements A map operation applies a function to each element of the input stream to produce another output stream. The number of elements in the input and output streams is the same. The operation does not modify the elements of the input stream. Example is here...
  • 25. ... Filtering the Stream elements The filter operation is applied on an input stream to produce another stream, which is known as the filtered stream. The returned stream by filter operation is a subset of the input stream. Example is here...
  • 26. ... Reducing the Stream elements The reduce operation combines all elements of a stream to produce a single value by applying a combining function repeatedly. It is also called reduction operation or a fold. Computing the sum, maximum, average, count, etc. of elements of a stream of integers are examples of the reduce operation. Streams API Provides us some specialized methods for reduce operation on Integers, Doubles and Floats.. Example is here...
  • 27. 5. Collecting data using Collectors. There are several cases in which we want to collect the results of executing a stream pipeline into a collection such as a List, a Set, a Map, etc. Sometimes we may want to apply complex logic to summarize the stream’s data. This is possible using the collect method. Example is here...
  • 28. ?