SlideShare a Scribd company logo
1 of 27
Functional programming in Java 8
07 juli 2016
Masudul Haque
Adapt : Learn functional programming
Java meets functional
programming (with
lambdas)
Java is not your grandma’s language anymore!
What is Lambda?
Before Lambda
List<Employee> employees = ...
double highestSalary = 0.0;
for (Employee e : employees) {
if (e.year == 2016) {
if (e.salary > highestSalary) {
highestSalary = e.salary;
}
}
}
• Client controls iteration
• Inherently serial: iterate from
beginning to end
• Not thread-safe
After Lambda
List<Employee> employees = ...
double highestSalary = employees.stream()
.filter(Employee e-> e.getYear() == 2016)
.map(e -> e.getSalary())
.max();
• More readable
• More abstract
• Less error-prone
• No reliance on mutable state
• Easier to make parallel
What is Lambda?
• Lambda expressions represent anonymous functions
– Like a method, has a typed argument list, a return type, a set of thrown exceptions, and
a body
– Not associated with a class
List<Employee> employees = ...
double highestSalary = employees.stream()
.filter(Employee e-> e.getYear() == 2016)
.map(e -> e.getSalary())
.max();
Predicate
Function
What is Lambda?
List<Employee> employees = ...
double highestSalary = employees.stream()
.filter(Employee e-> e.getYear() == 2016)
.map(e -> e.getSalary())
.max();
• Stream<T> filter(Predicate<? super T> predicate)
• Filter objects that match a Predicate object
• <R> Stream<R> map(Function<? super T, ? extends R> mapper)
• Map objects to another value as specified by a Function object
Predicate
Function
What is Functional programming?
• Functional languages view programs as an entity— called a function—
that accepts inputs and produces output
• Functions are connected together by their outputs to other functions’
inputs.
• Underlying approach: “Evaluate an expression. Then use the results for
something else.”
Example
Runnable r = new Runnable(){
public void run(){
System.out.println("Hello World");
}
};
Runnable r =()-> System.out.println("Hello World");
Stream
What is Stream?
• A Typed Interface.
public interface Stream<T> extends BaseStream<T,Stream<T>>
• Abstraction for specifying aggregate computations
– Not a data structure
– Can be infinite
• Simplifies the description of aggregate computations
– Exposes opportunitires for optimisation
– Fusing, laziness and parrallelism
What is Stream?
• What can I do with it?
Answer: efficiently process high volumes of data, but also small ones.
• What does efficiently mean?
Two things:
1. In parallel, to leverage multicore CPU
2. In pipeline, to avoid the computation of intermediate data structures
Stream Pipeline
A stream pipeline consists of three types of things
1. A source
2. Zero or more intermediate operations
3. A terminal operation
List<Employee> employees = ...
double highestSalary = employees.stream()
.filter(Employee e-> e.getYear() == 2016)
.map(e -> e.getSalary())
.max(); Intemediate
Operation
Source
Terminal
Operation
Intemediate
Operations
stream pipeline
Stream
source
Intermediate
operations
Terminal
operation
stream
stream
Examples:
IntStream.range(),
Arrays.stream()
Examples:
map(), filter(),
distinct(), sorted()
Examples:
sum(), collect(),
forEach(), reduce()
DoubleStream.
of(1.0, 4.0, 9.0)
map(Math::sqrt)
.peek(System.out::
println)
Stream
Source (with
elements 1.0,
4.0, and 9.0)
Intermediate
Operation 1
(maps to
element values
1.0, 2.0, and 3.0)
Intermediate
Operation 2
(prints 1.0, 2.0,
and 3.0)
.sum();
Terminal
Operation
(returns the
sum 6.0)
DoubleStream.of(1.0, 4.0, 9.0)
.map(Math::sqrt)
.peek(System.out::println)
.sum();
Stream.of (1, 2, 3, 4, 5)
.map(i -> i * i)
.peek(i -> System.out.printf("%d ",i))
.count();
prints: 1 4 9 16 25
Demo
long startTime = System.currentTimeMillis();
long numOfPrimes = LongStream.rangeClosed(2, 10_000_000)
.filter(PrimeNumbers::isPrime)
.count();
System.out.println(numOfPrimes);
long endTime = System.currentTimeMillis();
System.out.printf( " Duration : %f %n ",(endTime - startTime)/1000.0);
Parallel code
Serial code
long numOfPrimes =LongStream.rangeClosed(2, 10_000_000)
.filter(PrimeNumbers::isPrime)
.count();
System.out.println(numOfPrimes);
Prints 664579
8.501 seconds
Parallel code
Serial code
Let’s flip the switch by
calling parallel() function
long numOfPrimes =LongStream.rangeClosed(2, 10_000_000)
.parallel()
.filter(PrimeNumbers::isPrime)
.count();
System.out.println(numOfPrimes);
Prints 664579
2.041 seconds
Wow! That’s an awesome flip
switch!
Internally, parallel streams make
use of fork-join framework
Q & A
Contact
For any question
Email: M.Haque@cimsolutions.nl
Follow me in following site:
Stackoverflow
http://stackoverflow.com/users/1265660/masud
Github
https://github.com/masudcse05
Blog
https://masudulhaque.wordpress.com

More Related Content

What's hot

Functional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singhFunctional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singhHarmeet Singh(Taara)
 
JavaScript - Chapter 6 - Basic Functions
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic FunctionsWebStackAcademy
 
Java 8 lambda expressions
Java 8 lambda expressionsJava 8 lambda expressions
Java 8 lambda expressionsLogan Chien
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypesVarun C M
 
Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java langer4711
 
Object Relational Mapping in PHP
Object Relational Mapping in PHPObject Relational Mapping in PHP
Object Relational Mapping in PHPRob Knight
 
Building Data Mapper PHP5
Building Data Mapper PHP5Building Data Mapper PHP5
Building Data Mapper PHP5Vance Lucas
 

What's hot (8)

Functional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singhFunctional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singh
 
JavaScript - Chapter 6 - Basic Functions
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic Functions
 
Java 8 lambda expressions
Java 8 lambda expressionsJava 8 lambda expressions
Java 8 lambda expressions
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
 
Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java
 
Object Relational Mapping in PHP
Object Relational Mapping in PHPObject Relational Mapping in PHP
Object Relational Mapping in PHP
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Building Data Mapper PHP5
Building Data Mapper PHP5Building Data Mapper PHP5
Building Data Mapper PHP5
 

Similar to Java 8 lambda

Introduction to javascript.ppt
Introduction to javascript.pptIntroduction to javascript.ppt
Introduction to javascript.pptBArulmozhi
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8Knoldus Inc.
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentationVan Huong
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streamsjessitron
 
Lessons Learnt With Lambdas and Streams in JDK 8
Lessons Learnt With Lambdas and Streams in JDK 8Lessons Learnt With Lambdas and Streams in JDK 8
Lessons Learnt With Lambdas and Streams in JDK 8Simon Ritter
 
How to debug slow lambda response times
How to debug slow lambda response timesHow to debug slow lambda response times
How to debug slow lambda response timesYan Cui
 
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
 
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
 

Similar to Java 8 lambda (20)

Lambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter LawreyLambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter Lawrey
 
Java 8
Java 8Java 8
Java 8
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Introduction to javascript.ppt
Introduction to javascript.pptIntroduction to javascript.ppt
Introduction to javascript.ppt
 
Java 8
Java 8Java 8
Java 8
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streams
 
Java8
Java8Java8
Java8
 
Lessons Learnt With Lambdas and Streams in JDK 8
Lessons Learnt With Lambdas and Streams in JDK 8Lessons Learnt With Lambdas and Streams in JDK 8
Lessons Learnt With Lambdas and Streams in JDK 8
 
java8
java8java8
java8
 
What`s New in Java 8
What`s New in Java 8What`s New in Java 8
What`s New in Java 8
 
How to debug slow lambda response times
How to debug slow lambda response timesHow to debug slow lambda response times
How to debug slow lambda response times
 
Java 8
Java 8Java 8
Java 8
 
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)
 
Oct.22nd.Presentation.Final
Oct.22nd.Presentation.FinalOct.22nd.Presentation.Final
Oct.22nd.Presentation.Final
 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
 
Matlab ppt
Matlab pptMatlab ppt
Matlab ppt
 
Java 8 Intro - Core Features
Java 8 Intro - Core FeaturesJava 8 Intro - Core Features
Java 8 Intro - Core Features
 
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
 

More from Masudul Haque

More from Masudul Haque (6)

Websocket
WebsocketWebsocket
Websocket
 
Java 9 new features
Java 9 new featuresJava 9 new features
Java 9 new features
 
Java-7: Collections
Java-7: CollectionsJava-7: Collections
Java-7: Collections
 
Java: Regular Expression
Java: Regular ExpressionJava: Regular Expression
Java: Regular Expression
 
Java-7 Concurrency
Java-7 ConcurrencyJava-7 Concurrency
Java-7 Concurrency
 
Basic java
Basic javaBasic java
Basic java
 

Recently uploaded

Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 

Recently uploaded (20)

Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 

Java 8 lambda

  • 1. Functional programming in Java 8 07 juli 2016 Masudul Haque
  • 2. Adapt : Learn functional programming
  • 4. Java is not your grandma’s language anymore!
  • 6. Before Lambda List<Employee> employees = ... double highestSalary = 0.0; for (Employee e : employees) { if (e.year == 2016) { if (e.salary > highestSalary) { highestSalary = e.salary; } } } • Client controls iteration • Inherently serial: iterate from beginning to end • Not thread-safe
  • 7. After Lambda List<Employee> employees = ... double highestSalary = employees.stream() .filter(Employee e-> e.getYear() == 2016) .map(e -> e.getSalary()) .max(); • More readable • More abstract • Less error-prone • No reliance on mutable state • Easier to make parallel
  • 8. What is Lambda? • Lambda expressions represent anonymous functions – Like a method, has a typed argument list, a return type, a set of thrown exceptions, and a body – Not associated with a class List<Employee> employees = ... double highestSalary = employees.stream() .filter(Employee e-> e.getYear() == 2016) .map(e -> e.getSalary()) .max(); Predicate Function
  • 9. What is Lambda? List<Employee> employees = ... double highestSalary = employees.stream() .filter(Employee e-> e.getYear() == 2016) .map(e -> e.getSalary()) .max(); • Stream<T> filter(Predicate<? super T> predicate) • Filter objects that match a Predicate object • <R> Stream<R> map(Function<? super T, ? extends R> mapper) • Map objects to another value as specified by a Function object Predicate Function
  • 10. What is Functional programming? • Functional languages view programs as an entity— called a function— that accepts inputs and produces output • Functions are connected together by their outputs to other functions’ inputs. • Underlying approach: “Evaluate an expression. Then use the results for something else.”
  • 11. Example Runnable r = new Runnable(){ public void run(){ System.out.println("Hello World"); } }; Runnable r =()-> System.out.println("Hello World");
  • 13. What is Stream? • A Typed Interface. public interface Stream<T> extends BaseStream<T,Stream<T>> • Abstraction for specifying aggregate computations – Not a data structure – Can be infinite • Simplifies the description of aggregate computations – Exposes opportunitires for optimisation – Fusing, laziness and parrallelism
  • 14. What is Stream? • What can I do with it? Answer: efficiently process high volumes of data, but also small ones. • What does efficiently mean? Two things: 1. In parallel, to leverage multicore CPU 2. In pipeline, to avoid the computation of intermediate data structures
  • 15. Stream Pipeline A stream pipeline consists of three types of things 1. A source 2. Zero or more intermediate operations 3. A terminal operation List<Employee> employees = ... double highestSalary = employees.stream() .filter(Employee e-> e.getYear() == 2016) .map(e -> e.getSalary()) .max(); Intemediate Operation Source Terminal Operation Intemediate Operations
  • 17. DoubleStream. of(1.0, 4.0, 9.0) map(Math::sqrt) .peek(System.out:: println) Stream Source (with elements 1.0, 4.0, and 9.0) Intermediate Operation 1 (maps to element values 1.0, 2.0, and 3.0) Intermediate Operation 2 (prints 1.0, 2.0, and 3.0) .sum(); Terminal Operation (returns the sum 6.0) DoubleStream.of(1.0, 4.0, 9.0) .map(Math::sqrt) .peek(System.out::println) .sum();
  • 18. Stream.of (1, 2, 3, 4, 5) .map(i -> i * i) .peek(i -> System.out.printf("%d ",i)) .count(); prints: 1 4 9 16 25
  • 19. Demo long startTime = System.currentTimeMillis(); long numOfPrimes = LongStream.rangeClosed(2, 10_000_000) .filter(PrimeNumbers::isPrime) .count(); System.out.println(numOfPrimes); long endTime = System.currentTimeMillis(); System.out.printf( " Duration : %f %n ",(endTime - startTime)/1000.0);
  • 21. long numOfPrimes =LongStream.rangeClosed(2, 10_000_000) .filter(PrimeNumbers::isPrime) .count(); System.out.println(numOfPrimes); Prints 664579 8.501 seconds
  • 22. Parallel code Serial code Let’s flip the switch by calling parallel() function
  • 23. long numOfPrimes =LongStream.rangeClosed(2, 10_000_000) .parallel() .filter(PrimeNumbers::isPrime) .count(); System.out.println(numOfPrimes); Prints 664579 2.041 seconds
  • 24. Wow! That’s an awesome flip switch!
  • 25. Internally, parallel streams make use of fork-join framework
  • 26. Q & A
  • 27. Contact For any question Email: M.Haque@cimsolutions.nl Follow me in following site: Stackoverflow http://stackoverflow.com/users/1265660/masud Github https://github.com/masudcse05 Blog https://masudulhaque.wordpress.com