SlideShare a Scribd company logo
Java SE 8 :Streams
Streams Part 1
1. Overview of Streams
2. Standard Data Structures Into and Out of Streams
3. Core Stream Methods:
3.1 forEach(), map(), filter(), findFirst()
3.2 reduce(), collect(), min(), max(), sorted(), distinct(), limit(), skip(),
noneMatch(), allMatch(), anyMatch(), count()
4. Lazy Evaluation
5. Wrap Up
1Lars Lemos, MCA, OCPJP SE 6
Streams Overview
Stream Idea
 Streams are wrappers around data sources such as arrays or lists. They provide
many high performance operations that can be expressed with lambdas,
executed sequentially or in parallel.
Example: StreamSamples.java
 Note: Streams are not collections. This appear to be an interactive process for n elements over
each method operation. But due to Lazy evaluation there are less iterations performed over each
condition being met.
2
Lars Lemos, MCA, OCPJP SE 6
Streams Overview
Stream Idea
 Streams are “Not data structures”, they have no storage. They carry values
from a source through a pipeline of operations.
 Streams are “Designed for Lambdas”, streams operations take lambdas as
arguments.
 Streams don’t have “Indexed access”, you can access the first element, but
not the second or third.
 Streams output “Arrays or Lists” easily with simple syntax.
 Streams are “Lazy”, the operations are postponed until it is known how much
data is eventually needed.
Example: A operation that takes 10 s/item on a 100 element Stream, selecting the 1st
element takes 10s not 10000s
 Streams are “Parallelizable”, once a stream is designated as parallel, then
operations will automatically be done in parallel without having to write
explicit multi-threading code.
 Streams can “Ubounded”, once a generator function is designated, clients
can consume entries as long as they want, with values being generated on the
fly.
3
Lars Lemos, MCA, OCPJP SE 6
Streams Overview
Creating Stream
 It’s known that streams are not collections: they do not manage their own
data (wrappers around data structures).
 Thus a stream does not copy the underlying data, only builds a pipeline of
operations. And it can be invoked when desired.
Syntax:
• Individual values - Stream.of(val1, val2, …);
• Array - Stream.of(objectArray);
• Lists - someList.stream();
• StreamBuilder – someBuilder.build();
• String - Stream.of(somestring.split());
4
Lars Lemos, MCA, OCPJP SE 6
Streams Overview
Stream from Primitives
– Alternatives
• int[] nums = { 1, 2, 3, 4 };
• Arrays.stream(nums)… // IntStream
• Integer[] nums = { 1, 2, 3, 4 };
• Arrays.stream(nums)… or Stream.of(nums)… // Stream<Integer>
• Making 1-item stream by accident
– Mistake
• int[] nums = { 1, 2, 3, 4 };
• Stream.of(nums)… // 1-item Stream containing array
– Correct
• Integer[] nums = { 1, 2, 3, 4 };
• Stream.of(nums)… // 4-item Stream containing Integers 5
Lars Lemos, MCA, OCPJP SE 6
Streams Overview
Streams to Pre-Java 8 Data Structures
 Array
– strm.toArray(EntryType[]::new)
Examples: employeeStream.toArray(Employee[]::new)
– The argument to toArray is normally EntryType[]::new, but in general is a
Supplier that takes an int (size) as an argument and returns an empty array that
can be filled in.
 List
– strm.collect(Collectors.toList())
• Common to do “import static java.util.stream.Collectors.*;”
then to do strm.collect(toList())
 Other collections
– strm.collect(Collectors.toSet()), – strm.collect(Collectors.groupingBy(…)),
etc.
 String
– strm.collect(Collectors.toStringJoiner(delim)).toString()
6
Lars Lemos, MCA, OCPJP SE 6
Streams Overview
Core Streams Methods
 forEach(Consumer) : employees.forEach(e -> e.setSalary(e.getSalary() * 11/10))
Example: forEachExamples();
 map(Function) : ids.map(EmployeeUtils::findEmployeeById)
Example: mapExamples()
 filter(Predicate) : employees.filter(e -> e.getSalary() > 500000)
Example: filterExamples();
 findFirst() : employees.filter(…).findFirst().get()
Example: combinedExamples();
 collect(Collectors.toList()) : List<Employee> empList = employees.collect(Collectors.toList());
Example: lazyEvaluationExample();
7
Lars Lemos, MCA, OCPJP SE 6
Streams Overview
8
Lars Lemos, MCA, OCPJP SE 6
End of part II
Part III – JavaScript in JVM, Nashorn
…………
larslemos@gmail.com
Lars Lemos
toplars
Ad

More Related Content

What's hot (6)

Linked list using Dynamic Memory Allocation
Linked list using Dynamic Memory AllocationLinked list using Dynamic Memory Allocation
Linked list using Dynamic Memory Allocation
kiran Patel
 
Starting work with R
Starting work with RStarting work with R
Starting work with R
Vladimir Bakhrushin
 
ADS Introduction
ADS IntroductionADS Introduction
ADS Introduction
NagendraK18
 
Day2 xslt x_path_xquery
Day2 xslt x_path_xqueryDay2 xslt x_path_xquery
Day2 xslt x_path_xquery
XAVIERCONSULTANTS
 
Analysis of algorithms
Analysis of algorithmsAnalysis of algorithms
Analysis of algorithms
iqbalphy1
 
Reservoir Computing Overview (with emphasis on Liquid State Machines)
Reservoir Computing Overview (with emphasis on Liquid State Machines)Reservoir Computing Overview (with emphasis on Liquid State Machines)
Reservoir Computing Overview (with emphasis on Liquid State Machines)
Alex Klibisz
 
Linked list using Dynamic Memory Allocation
Linked list using Dynamic Memory AllocationLinked list using Dynamic Memory Allocation
Linked list using Dynamic Memory Allocation
kiran Patel
 
ADS Introduction
ADS IntroductionADS Introduction
ADS Introduction
NagendraK18
 
Analysis of algorithms
Analysis of algorithmsAnalysis of algorithms
Analysis of algorithms
iqbalphy1
 
Reservoir Computing Overview (with emphasis on Liquid State Machines)
Reservoir Computing Overview (with emphasis on Liquid State Machines)Reservoir Computing Overview (with emphasis on Liquid State Machines)
Reservoir Computing Overview (with emphasis on Liquid State Machines)
Alex Klibisz
 

Similar to Java se 8 streams pt1 (20)

Java Advanced Topic - Streams Presentations
Java Advanced Topic - Streams PresentationsJava Advanced Topic - Streams Presentations
Java Advanced Topic - Streams Presentations
MuraliD32
 
MLconf NYC Xiangrui Meng
MLconf NYC Xiangrui MengMLconf NYC Xiangrui Meng
MLconf NYC Xiangrui Meng
MLconf
 
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
 
JavaCro'15 - Elasticsearch as a search alternative to a relational database -...
JavaCro'15 - Elasticsearch as a search alternative to a relational database -...JavaCro'15 - Elasticsearch as a search alternative to a relational database -...
JavaCro'15 - Elasticsearch as a search alternative to a relational database -...
HUJAK - Hrvatska udruga Java korisnika / Croatian Java User Association
 
Elasticsearch as a search alternative to a relational database
Elasticsearch as a search alternative to a relational databaseElasticsearch as a search alternative to a relational database
Elasticsearch as a search alternative to a relational database
Kristijan Duvnjak
 
Tulsa techfest Spark Core Aug 5th 2016
Tulsa techfest Spark Core Aug 5th 2016Tulsa techfest Spark Core Aug 5th 2016
Tulsa techfest Spark Core Aug 5th 2016
Mark Smith
 
Real Time Big Data Management
Real Time Big Data ManagementReal Time Big Data Management
Real Time Big Data Management
Albert Bifet
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streams
jessitron
 
Clustering and Visualisation using R programming
Clustering and Visualisation using R programmingClustering and Visualisation using R programming
Clustering and Visualisation using R programming
Nixon Mendez
 
Apache SystemML Optimizer and Runtime techniques by Matthias Boehm
Apache SystemML Optimizer and Runtime techniques by Matthias BoehmApache SystemML Optimizer and Runtime techniques by Matthias Boehm
Apache SystemML Optimizer and Runtime techniques by Matthias Boehm
Arvind Surve
 
Apache SystemML Optimizer and Runtime techniques by Matthias Boehm
Apache SystemML Optimizer and Runtime techniques by Matthias BoehmApache SystemML Optimizer and Runtime techniques by Matthias Boehm
Apache SystemML Optimizer and Runtime techniques by Matthias Boehm
Arvind Surve
 
Performance and predictability (1)
Performance and predictability (1)Performance and predictability (1)
Performance and predictability (1)
RichardWarburton
 
Performance and Predictability - Richard Warburton
Performance and Predictability - Richard WarburtonPerformance and Predictability - Richard Warburton
Performance and Predictability - Richard Warburton
JAXLondon2014
 
Advanced Data Science on Spark-(Reza Zadeh, Stanford)
Advanced Data Science on Spark-(Reza Zadeh, Stanford)Advanced Data Science on Spark-(Reza Zadeh, Stanford)
Advanced Data Science on Spark-(Reza Zadeh, Stanford)
Spark Summit
 
Java 8 Streams
Java 8 StreamsJava 8 Streams
Java 8 Streams
Manvendra Singh
 
Introduction to parallel and distributed computation with spark
Introduction to parallel and distributed computation with sparkIntroduction to parallel and distributed computation with spark
Introduction to parallel and distributed computation with spark
Angelo Leto
 
Cassandra for Sysadmins
Cassandra for SysadminsCassandra for Sysadmins
Cassandra for Sysadmins
Nathan Milford
 
Apache Flink Deep Dive
Apache Flink Deep DiveApache Flink Deep Dive
Apache Flink Deep Dive
DataWorks Summit
 
Powering a Graph Data System with Scylla + JanusGraph
Powering a Graph Data System with Scylla + JanusGraphPowering a Graph Data System with Scylla + JanusGraph
Powering a Graph Data System with Scylla + JanusGraph
ScyllaDB
 
Java Advanced Topic - Streams Presentations
Java Advanced Topic - Streams PresentationsJava Advanced Topic - Streams Presentations
Java Advanced Topic - Streams Presentations
MuraliD32
 
MLconf NYC Xiangrui Meng
MLconf NYC Xiangrui MengMLconf NYC Xiangrui Meng
MLconf NYC Xiangrui Meng
MLconf
 
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
 
Elasticsearch as a search alternative to a relational database
Elasticsearch as a search alternative to a relational databaseElasticsearch as a search alternative to a relational database
Elasticsearch as a search alternative to a relational database
Kristijan Duvnjak
 
Tulsa techfest Spark Core Aug 5th 2016
Tulsa techfest Spark Core Aug 5th 2016Tulsa techfest Spark Core Aug 5th 2016
Tulsa techfest Spark Core Aug 5th 2016
Mark Smith
 
Real Time Big Data Management
Real Time Big Data ManagementReal Time Big Data Management
Real Time Big Data Management
Albert Bifet
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streams
jessitron
 
Clustering and Visualisation using R programming
Clustering and Visualisation using R programmingClustering and Visualisation using R programming
Clustering and Visualisation using R programming
Nixon Mendez
 
Apache SystemML Optimizer and Runtime techniques by Matthias Boehm
Apache SystemML Optimizer and Runtime techniques by Matthias BoehmApache SystemML Optimizer and Runtime techniques by Matthias Boehm
Apache SystemML Optimizer and Runtime techniques by Matthias Boehm
Arvind Surve
 
Apache SystemML Optimizer and Runtime techniques by Matthias Boehm
Apache SystemML Optimizer and Runtime techniques by Matthias BoehmApache SystemML Optimizer and Runtime techniques by Matthias Boehm
Apache SystemML Optimizer and Runtime techniques by Matthias Boehm
Arvind Surve
 
Performance and predictability (1)
Performance and predictability (1)Performance and predictability (1)
Performance and predictability (1)
RichardWarburton
 
Performance and Predictability - Richard Warburton
Performance and Predictability - Richard WarburtonPerformance and Predictability - Richard Warburton
Performance and Predictability - Richard Warburton
JAXLondon2014
 
Advanced Data Science on Spark-(Reza Zadeh, Stanford)
Advanced Data Science on Spark-(Reza Zadeh, Stanford)Advanced Data Science on Spark-(Reza Zadeh, Stanford)
Advanced Data Science on Spark-(Reza Zadeh, Stanford)
Spark Summit
 
Introduction to parallel and distributed computation with spark
Introduction to parallel and distributed computation with sparkIntroduction to parallel and distributed computation with spark
Introduction to parallel and distributed computation with spark
Angelo Leto
 
Cassandra for Sysadmins
Cassandra for SysadminsCassandra for Sysadmins
Cassandra for Sysadmins
Nathan Milford
 
Powering a Graph Data System with Scylla + JanusGraph
Powering a Graph Data System with Scylla + JanusGraphPowering a Graph Data System with Scylla + JanusGraph
Powering a Graph Data System with Scylla + JanusGraph
ScyllaDB
 
Ad

Recently uploaded (20)

Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World ExamplesMastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
jamescantor38
 
The Elixir Developer - All Things Open
The Elixir Developer - All Things OpenThe Elixir Developer - All Things Open
The Elixir Developer - All Things Open
Carlo Gilmar Padilla Santana
 
Why Tapitag Ranks Among the Best Digital Business Card Providers
Why Tapitag Ranks Among the Best Digital Business Card ProvidersWhy Tapitag Ranks Among the Best Digital Business Card Providers
Why Tapitag Ranks Among the Best Digital Business Card Providers
Tapitag
 
From Vibe Coding to Vibe Testing - Complete PowerPoint Presentation
From Vibe Coding to Vibe Testing - Complete PowerPoint PresentationFrom Vibe Coding to Vibe Testing - Complete PowerPoint Presentation
From Vibe Coding to Vibe Testing - Complete PowerPoint Presentation
Shay Ginsbourg
 
Buy vs. Build: Unlocking the right path for your training tech
Buy vs. Build: Unlocking the right path for your training techBuy vs. Build: Unlocking the right path for your training tech
Buy vs. Build: Unlocking the right path for your training tech
Rustici Software
 
Wilcom Embroidery Studio Crack 2025 For Windows
Wilcom Embroidery Studio Crack 2025 For WindowsWilcom Embroidery Studio Crack 2025 For Windows
Wilcom Embroidery Studio Crack 2025 For Windows
Google
 
What Do Candidates Really Think About AI-Powered Recruitment Tools?
What Do Candidates Really Think About AI-Powered Recruitment Tools?What Do Candidates Really Think About AI-Powered Recruitment Tools?
What Do Candidates Really Think About AI-Powered Recruitment Tools?
HireME
 
Sequence Diagrams With Pictures (1).pptx
Sequence Diagrams With Pictures (1).pptxSequence Diagrams With Pictures (1).pptx
Sequence Diagrams With Pictures (1).pptx
aashrithakondapalli8
 
Download MathType Crack Version 2025???
Download MathType Crack  Version 2025???Download MathType Crack  Version 2025???
Download MathType Crack Version 2025???
Google
 
GDS SYSTEM | GLOBAL DISTRIBUTION SYSTEM
GDS SYSTEM | GLOBAL  DISTRIBUTION SYSTEMGDS SYSTEM | GLOBAL  DISTRIBUTION SYSTEM
GDS SYSTEM | GLOBAL DISTRIBUTION SYSTEM
philipnathen82
 
The-Future-is-Hybrid-Exploring-Azure’s-Role-in-Multi-Cloud-Strategies.pptx
The-Future-is-Hybrid-Exploring-Azure’s-Role-in-Multi-Cloud-Strategies.pptxThe-Future-is-Hybrid-Exploring-Azure’s-Role-in-Multi-Cloud-Strategies.pptx
The-Future-is-Hybrid-Exploring-Azure’s-Role-in-Multi-Cloud-Strategies.pptx
james brownuae
 
Mobile Application Developer Dubai | Custom App Solutions by Ajath
Mobile Application Developer Dubai | Custom App Solutions by AjathMobile Application Developer Dubai | Custom App Solutions by Ajath
Mobile Application Developer Dubai | Custom App Solutions by Ajath
Ajath Infotech Technologies LLC
 
sequencediagrams.pptx software Engineering
sequencediagrams.pptx software Engineeringsequencediagrams.pptx software Engineering
sequencediagrams.pptx software Engineering
aashrithakondapalli8
 
Exchange Migration Tool- Shoviv Software
Exchange Migration Tool- Shoviv SoftwareExchange Migration Tool- Shoviv Software
Exchange Migration Tool- Shoviv Software
Shoviv Software
 
How to Troubleshoot 9 Types of OutOfMemoryError
How to Troubleshoot 9 Types of OutOfMemoryErrorHow to Troubleshoot 9 Types of OutOfMemoryError
How to Troubleshoot 9 Types of OutOfMemoryError
Tier1 app
 
Programs as Values - Write code and don't get lost
Programs as Values - Write code and don't get lostPrograms as Values - Write code and don't get lost
Programs as Values - Write code and don't get lost
Pierangelo Cecchetto
 
wAIred_LearnWithOutAI_JCON_14052025.pptx
wAIred_LearnWithOutAI_JCON_14052025.pptxwAIred_LearnWithOutAI_JCON_14052025.pptx
wAIred_LearnWithOutAI_JCON_14052025.pptx
SimonedeGijt
 
Top 12 Most Useful AngularJS Development Tools to Use in 2025
Top 12 Most Useful AngularJS Development Tools to Use in 2025Top 12 Most Useful AngularJS Development Tools to Use in 2025
Top 12 Most Useful AngularJS Development Tools to Use in 2025
GrapesTech Solutions
 
Solar-wind hybrid engery a system sustainable power
Solar-wind  hybrid engery a system sustainable powerSolar-wind  hybrid engery a system sustainable power
Solar-wind hybrid engery a system sustainable power
bhoomigowda12345
 
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
OnePlan Solutions
 
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World ExamplesMastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
jamescantor38
 
Why Tapitag Ranks Among the Best Digital Business Card Providers
Why Tapitag Ranks Among the Best Digital Business Card ProvidersWhy Tapitag Ranks Among the Best Digital Business Card Providers
Why Tapitag Ranks Among the Best Digital Business Card Providers
Tapitag
 
From Vibe Coding to Vibe Testing - Complete PowerPoint Presentation
From Vibe Coding to Vibe Testing - Complete PowerPoint PresentationFrom Vibe Coding to Vibe Testing - Complete PowerPoint Presentation
From Vibe Coding to Vibe Testing - Complete PowerPoint Presentation
Shay Ginsbourg
 
Buy vs. Build: Unlocking the right path for your training tech
Buy vs. Build: Unlocking the right path for your training techBuy vs. Build: Unlocking the right path for your training tech
Buy vs. Build: Unlocking the right path for your training tech
Rustici Software
 
Wilcom Embroidery Studio Crack 2025 For Windows
Wilcom Embroidery Studio Crack 2025 For WindowsWilcom Embroidery Studio Crack 2025 For Windows
Wilcom Embroidery Studio Crack 2025 For Windows
Google
 
What Do Candidates Really Think About AI-Powered Recruitment Tools?
What Do Candidates Really Think About AI-Powered Recruitment Tools?What Do Candidates Really Think About AI-Powered Recruitment Tools?
What Do Candidates Really Think About AI-Powered Recruitment Tools?
HireME
 
Sequence Diagrams With Pictures (1).pptx
Sequence Diagrams With Pictures (1).pptxSequence Diagrams With Pictures (1).pptx
Sequence Diagrams With Pictures (1).pptx
aashrithakondapalli8
 
Download MathType Crack Version 2025???
Download MathType Crack  Version 2025???Download MathType Crack  Version 2025???
Download MathType Crack Version 2025???
Google
 
GDS SYSTEM | GLOBAL DISTRIBUTION SYSTEM
GDS SYSTEM | GLOBAL  DISTRIBUTION SYSTEMGDS SYSTEM | GLOBAL  DISTRIBUTION SYSTEM
GDS SYSTEM | GLOBAL DISTRIBUTION SYSTEM
philipnathen82
 
The-Future-is-Hybrid-Exploring-Azure’s-Role-in-Multi-Cloud-Strategies.pptx
The-Future-is-Hybrid-Exploring-Azure’s-Role-in-Multi-Cloud-Strategies.pptxThe-Future-is-Hybrid-Exploring-Azure’s-Role-in-Multi-Cloud-Strategies.pptx
The-Future-is-Hybrid-Exploring-Azure’s-Role-in-Multi-Cloud-Strategies.pptx
james brownuae
 
Mobile Application Developer Dubai | Custom App Solutions by Ajath
Mobile Application Developer Dubai | Custom App Solutions by AjathMobile Application Developer Dubai | Custom App Solutions by Ajath
Mobile Application Developer Dubai | Custom App Solutions by Ajath
Ajath Infotech Technologies LLC
 
sequencediagrams.pptx software Engineering
sequencediagrams.pptx software Engineeringsequencediagrams.pptx software Engineering
sequencediagrams.pptx software Engineering
aashrithakondapalli8
 
Exchange Migration Tool- Shoviv Software
Exchange Migration Tool- Shoviv SoftwareExchange Migration Tool- Shoviv Software
Exchange Migration Tool- Shoviv Software
Shoviv Software
 
How to Troubleshoot 9 Types of OutOfMemoryError
How to Troubleshoot 9 Types of OutOfMemoryErrorHow to Troubleshoot 9 Types of OutOfMemoryError
How to Troubleshoot 9 Types of OutOfMemoryError
Tier1 app
 
Programs as Values - Write code and don't get lost
Programs as Values - Write code and don't get lostPrograms as Values - Write code and don't get lost
Programs as Values - Write code and don't get lost
Pierangelo Cecchetto
 
wAIred_LearnWithOutAI_JCON_14052025.pptx
wAIred_LearnWithOutAI_JCON_14052025.pptxwAIred_LearnWithOutAI_JCON_14052025.pptx
wAIred_LearnWithOutAI_JCON_14052025.pptx
SimonedeGijt
 
Top 12 Most Useful AngularJS Development Tools to Use in 2025
Top 12 Most Useful AngularJS Development Tools to Use in 2025Top 12 Most Useful AngularJS Development Tools to Use in 2025
Top 12 Most Useful AngularJS Development Tools to Use in 2025
GrapesTech Solutions
 
Solar-wind hybrid engery a system sustainable power
Solar-wind  hybrid engery a system sustainable powerSolar-wind  hybrid engery a system sustainable power
Solar-wind hybrid engery a system sustainable power
bhoomigowda12345
 
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
OnePlan Solutions
 
Ad

Java se 8 streams pt1

  • 1. Java SE 8 :Streams Streams Part 1 1. Overview of Streams 2. Standard Data Structures Into and Out of Streams 3. Core Stream Methods: 3.1 forEach(), map(), filter(), findFirst() 3.2 reduce(), collect(), min(), max(), sorted(), distinct(), limit(), skip(), noneMatch(), allMatch(), anyMatch(), count() 4. Lazy Evaluation 5. Wrap Up 1Lars Lemos, MCA, OCPJP SE 6
  • 2. Streams Overview Stream Idea  Streams are wrappers around data sources such as arrays or lists. They provide many high performance operations that can be expressed with lambdas, executed sequentially or in parallel. Example: StreamSamples.java  Note: Streams are not collections. This appear to be an interactive process for n elements over each method operation. But due to Lazy evaluation there are less iterations performed over each condition being met. 2 Lars Lemos, MCA, OCPJP SE 6
  • 3. Streams Overview Stream Idea  Streams are “Not data structures”, they have no storage. They carry values from a source through a pipeline of operations.  Streams are “Designed for Lambdas”, streams operations take lambdas as arguments.  Streams don’t have “Indexed access”, you can access the first element, but not the second or third.  Streams output “Arrays or Lists” easily with simple syntax.  Streams are “Lazy”, the operations are postponed until it is known how much data is eventually needed. Example: A operation that takes 10 s/item on a 100 element Stream, selecting the 1st element takes 10s not 10000s  Streams are “Parallelizable”, once a stream is designated as parallel, then operations will automatically be done in parallel without having to write explicit multi-threading code.  Streams can “Ubounded”, once a generator function is designated, clients can consume entries as long as they want, with values being generated on the fly. 3 Lars Lemos, MCA, OCPJP SE 6
  • 4. Streams Overview Creating Stream  It’s known that streams are not collections: they do not manage their own data (wrappers around data structures).  Thus a stream does not copy the underlying data, only builds a pipeline of operations. And it can be invoked when desired. Syntax: • Individual values - Stream.of(val1, val2, …); • Array - Stream.of(objectArray); • Lists - someList.stream(); • StreamBuilder – someBuilder.build(); • String - Stream.of(somestring.split()); 4 Lars Lemos, MCA, OCPJP SE 6
  • 5. Streams Overview Stream from Primitives – Alternatives • int[] nums = { 1, 2, 3, 4 }; • Arrays.stream(nums)… // IntStream • Integer[] nums = { 1, 2, 3, 4 }; • Arrays.stream(nums)… or Stream.of(nums)… // Stream<Integer> • Making 1-item stream by accident – Mistake • int[] nums = { 1, 2, 3, 4 }; • Stream.of(nums)… // 1-item Stream containing array – Correct • Integer[] nums = { 1, 2, 3, 4 }; • Stream.of(nums)… // 4-item Stream containing Integers 5 Lars Lemos, MCA, OCPJP SE 6
  • 6. Streams Overview Streams to Pre-Java 8 Data Structures  Array – strm.toArray(EntryType[]::new) Examples: employeeStream.toArray(Employee[]::new) – The argument to toArray is normally EntryType[]::new, but in general is a Supplier that takes an int (size) as an argument and returns an empty array that can be filled in.  List – strm.collect(Collectors.toList()) • Common to do “import static java.util.stream.Collectors.*;” then to do strm.collect(toList())  Other collections – strm.collect(Collectors.toSet()), – strm.collect(Collectors.groupingBy(…)), etc.  String – strm.collect(Collectors.toStringJoiner(delim)).toString() 6 Lars Lemos, MCA, OCPJP SE 6
  • 7. Streams Overview Core Streams Methods  forEach(Consumer) : employees.forEach(e -> e.setSalary(e.getSalary() * 11/10)) Example: forEachExamples();  map(Function) : ids.map(EmployeeUtils::findEmployeeById) Example: mapExamples()  filter(Predicate) : employees.filter(e -> e.getSalary() > 500000) Example: filterExamples();  findFirst() : employees.filter(…).findFirst().get() Example: combinedExamples();  collect(Collectors.toList()) : List<Employee> empList = employees.collect(Collectors.toList()); Example: lazyEvaluationExample(); 7 Lars Lemos, MCA, OCPJP SE 6
  • 8. Streams Overview 8 Lars Lemos, MCA, OCPJP SE 6 End of part II Part III – JavaScript in JVM, Nashorn ………… larslemos@gmail.com Lars Lemos toplars
  翻译: