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

More Related Content

What's hot

Linked list using Dynamic Memory Allocation
Linked list using Dynamic Memory AllocationLinked list using Dynamic Memory Allocation
Linked list using Dynamic Memory Allocationkiran Patel
 
ADS Introduction
ADS IntroductionADS Introduction
ADS IntroductionNagendraK18
 
Analysis of algorithms
Analysis of algorithmsAnalysis of algorithms
Analysis of algorithmsiqbalphy1
 
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
 

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
 
Starting work with R
Starting work with RStarting work with R
Starting work with R
 
ADS Introduction
ADS IntroductionADS Introduction
ADS Introduction
 
Day2 xslt x_path_xquery
Day2 xslt x_path_xqueryDay2 xslt x_path_xquery
Day2 xslt x_path_xquery
 
Analysis of algorithms
Analysis of algorithmsAnalysis of algorithms
Analysis of algorithms
 
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)
 

Similar to Java se 8 streams pt1

MLconf NYC Xiangrui Meng
MLconf NYC Xiangrui MengMLconf NYC Xiangrui Meng
MLconf NYC Xiangrui MengMLconf
 
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 databaseKristijan 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 2016Mark Smith
 
Real Time Big Data Management
Real Time Big Data ManagementReal Time Big Data Management
Real Time Big Data ManagementAlbert Bifet
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streamsjessitron
 
Clustering and Visualisation using R programming
Clustering and Visualisation using R programmingClustering and Visualisation using R programming
Clustering and Visualisation using R programmingNixon 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 BoehmArvind 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 BoehmArvind 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 WarburtonJAXLondon2014
 
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 sparkAngelo Leto
 
Cassandra for Sysadmins
Cassandra for SysadminsCassandra for Sysadmins
Cassandra for SysadminsNathan 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 + JanusGraphScyllaDB
 
From Postgres to Cassandra (Rimas Silkaitis, Heroku) | C* Summit 2016
From Postgres to Cassandra (Rimas Silkaitis, Heroku) | C* Summit 2016From Postgres to Cassandra (Rimas Silkaitis, Heroku) | C* Summit 2016
From Postgres to Cassandra (Rimas Silkaitis, Heroku) | C* Summit 2016DataStax
 

Similar to Java se 8 streams pt1 (20)

MLconf NYC Xiangrui Meng
MLconf NYC Xiangrui MengMLconf NYC Xiangrui Meng
MLconf NYC Xiangrui Meng
 
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 ...
 
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
 
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 -...
 
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
 
Real Time Big Data Management
Real Time Big Data ManagementReal Time Big Data Management
Real Time Big Data Management
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streams
 
Clustering and Visualisation using R programming
Clustering and Visualisation using R programmingClustering and Visualisation using R programming
Clustering and Visualisation using R programming
 
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
 
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
 
Performance and predictability (1)
Performance and predictability (1)Performance and predictability (1)
Performance and predictability (1)
 
Performance and Predictability - Richard Warburton
Performance and Predictability - Richard WarburtonPerformance and Predictability - Richard Warburton
Performance and Predictability - Richard Warburton
 
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)
 
Java 8 Streams
Java 8 StreamsJava 8 Streams
Java 8 Streams
 
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
 
Cassandra for Sysadmins
Cassandra for SysadminsCassandra for Sysadmins
Cassandra for Sysadmins
 
Apache Flink Deep Dive
Apache Flink Deep DiveApache Flink Deep Dive
Apache Flink Deep Dive
 
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
 
From Postgres to Cassandra (Rimas Silkaitis, Heroku) | C* Summit 2016
From Postgres to Cassandra (Rimas Silkaitis, Heroku) | C* Summit 2016From Postgres to Cassandra (Rimas Silkaitis, Heroku) | C* Summit 2016
From Postgres to Cassandra (Rimas Silkaitis, Heroku) | C* Summit 2016
 

Recently uploaded

Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsMehedi Hasan Shohan
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 

Recently uploaded (20)

Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 

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