SlideShare a Scribd company logo
1 of 29
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)

Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
Event In JavaScript
Event In JavaScriptEvent In JavaScript
Event In JavaScript
 
React Hooks
React HooksReact Hooks
React Hooks
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
Angular Directives
Angular DirectivesAngular Directives
Angular Directives
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
 
Lambda Expressions in Java 8
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Optional in Java 8
Optional in Java 8Optional in Java 8
Optional in Java 8
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
testng
testngtestng
testng
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Generics in java
Generics in javaGenerics in java
Generics in java
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
jQuery
jQueryjQuery
jQuery
 
java 8 new features
java 8 new features java 8 new features
java 8 new features
 
C# Delegates
C# DelegatesC# Delegates
C# Delegates
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with Mockito
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
 

Viewers also liked

Java SE 9 modules (JPMS) - an introduction
Java SE 9 modules (JPMS) - an introductionJava SE 9 modules (JPMS) - an introduction
Java SE 9 modules (JPMS) - an introductionStephen Colebourne
 
Lambda Expressions in Java
Lambda Expressions in JavaLambda Expressions in Java
Lambda Expressions in JavaErhan Bagdemir
 
Working With Concurrency In Java 8
Working With Concurrency In Java 8Working With Concurrency In Java 8
Working With Concurrency In Java 8Heartin Jacob
 
Java9 Beyond Modularity - Java 9 más allá de la modularidad
Java9 Beyond Modularity - Java 9 más allá de la modularidadJava9 Beyond Modularity - Java 9 más allá de la modularidad
Java9 Beyond Modularity - Java 9 más allá de la modularidadDavid Gómez García
 
Java 9 Modules: The Duke Yet Lives That OSGi Shall Depose
Java 9 Modules: The Duke Yet Lives That OSGi Shall DeposeJava 9 Modules: The Duke Yet Lives That OSGi Shall Depose
Java 9 Modules: The Duke Yet Lives That OSGi Shall DeposeNikita Lipsky
 
Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsJava 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsNewCircle Training
 
The do's and don'ts with java 9 (Devoxx 2017)
The do's and don'ts with java 9 (Devoxx 2017)The do's and don'ts with java 9 (Devoxx 2017)
The do's and don'ts with java 9 (Devoxx 2017)Robert Scholte
 
Real World Java 9
Real World Java 9Real World Java 9
Real World Java 9Trisha Gee
 

Viewers also liked (10)

Java SE 9 modules (JPMS) - an introduction
Java SE 9 modules (JPMS) - an introductionJava SE 9 modules (JPMS) - an introduction
Java SE 9 modules (JPMS) - an introduction
 
Lambda Expressions in Java
Lambda Expressions in JavaLambda Expressions in Java
Lambda Expressions in Java
 
Java 9, JShell, and Modularity
Java 9, JShell, and ModularityJava 9, JShell, and Modularity
Java 9, JShell, and Modularity
 
Working With Concurrency In Java 8
Working With Concurrency In Java 8Working With Concurrency In Java 8
Working With Concurrency In Java 8
 
Java9 Beyond Modularity - Java 9 más allá de la modularidad
Java9 Beyond Modularity - Java 9 más allá de la modularidadJava9 Beyond Modularity - Java 9 más allá de la modularidad
Java9 Beyond Modularity - Java 9 más allá de la modularidad
 
Java 9 Modules: The Duke Yet Lives That OSGi Shall Depose
Java 9 Modules: The Duke Yet Lives That OSGi Shall DeposeJava 9 Modules: The Duke Yet Lives That OSGi Shall Depose
Java 9 Modules: The Duke Yet Lives That OSGi Shall Depose
 
Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsJava 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & Streams
 
Parallel streams in java 8
Parallel streams in java 8Parallel streams in java 8
Parallel streams in java 8
 
The do's and don'ts with java 9 (Devoxx 2017)
The do's and don'ts with java 9 (Devoxx 2017)The do's and don'ts with java 9 (Devoxx 2017)
The do's and don'ts with java 9 (Devoxx 2017)
 
Real World Java 9
Real World Java 9Real World Java 9
Real World Java 9
 

Similar to Java 8 Streams

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
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streamsjessitron
 
(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_iiNico Ludwig
 
(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_iiNico Ludwig
 
Synapse india complain sharing info on chapter 8 operator overloading
Synapse india complain sharing info on chapter 8   operator overloadingSynapse india complain sharing info on chapter 8   operator overloading
Synapse india complain sharing info on chapter 8 operator overloadingSynapseindiaComplaints
 
Java 8 Streams And Common Operations By Harmeet Singh(Taara)
Java 8 Streams And Common Operations By Harmeet Singh(Taara)Java 8 Streams And Common Operations By Harmeet Singh(Taara)
Java 8 Streams And Common Operations By Harmeet Singh(Taara)Harmeet Singh(Taara)
 
Harnessing the Power of Java 8 Streams
Harnessing the Power of Java 8 Streams Harnessing the Power of Java 8 Streams
Harnessing the Power of Java 8 Streams IndicThreads
 
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
 

Similar to Java 8 Streams (20)

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
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streams
 
(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii
 
java8
java8java8
java8
 
(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii
 
Streams in Java 8
Streams in Java 8Streams in Java 8
Streams in Java 8
 
Java 8 Intro - Core Features
Java 8 Intro - Core FeaturesJava 8 Intro - Core Features
Java 8 Intro - Core Features
 
Synapse india complain sharing info on chapter 8 operator overloading
Synapse india complain sharing info on chapter 8   operator overloadingSynapse india complain sharing info on chapter 8   operator overloading
Synapse india complain sharing info on chapter 8 operator overloading
 
Java8
Java8Java8
Java8
 
Lambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter LawreyLambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter Lawrey
 
JDK8 Streams
JDK8 StreamsJDK8 Streams
JDK8 Streams
 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
 
Java 8 Streams And Common Operations By Harmeet Singh(Taara)
Java 8 Streams And Common Operations By Harmeet Singh(Taara)Java 8 Streams And Common Operations By Harmeet Singh(Taara)
Java 8 Streams And Common Operations By Harmeet Singh(Taara)
 
Harnessing the Power of Java 8 Streams
Harnessing the Power of Java 8 Streams Harnessing the Power of Java 8 Streams
Harnessing the Power of Java 8 Streams
 
Java 8
Java 8Java 8
Java 8
 
Lambda Functions in Java 8
Lambda Functions in Java 8Lambda Functions in Java 8
Lambda Functions in Java 8
 
Hot Streaming Java
Hot Streaming JavaHot Streaming Java
Hot Streaming Java
 
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 ...
 
Unit v
Unit vUnit v
Unit v
 

Recently uploaded

%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrainmasabamasaba
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastPapp Krisztián
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...masabamasaba
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...masabamasaba
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Bert Jan Schrijver
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdfPearlKirahMaeRagusta1
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareJim McKeeth
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Hararemasabamasaba
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...SelfMade bd
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is insideshinachiaurasa2
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfkalichargn70th171
 

Recently uploaded (20)

%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 

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 git@github.com: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. ?