SlideShare ist ein Scribd-Unternehmen logo
1 von 15
Java 8 : Monads
Generics: Have Typed Containers
List list = new ArrayList();
list.add("one");
list.add(1);
list.add(1L);
list.add(new Object());
Before After
List<String> list = new ArrayList<>();
list.add("one");
list.add("1");
list.add(“1212”);
Typed ContainerContainer
A Thing we cannot do with containers
Transform container of String to a container of Integers
Monad: {Type Constructor, Bind, Return}
Optional Stream
Type Constructor of of
Bind map map
Return get collect
Example:
Stream.of(1,2,3,4,5).map(i -> i + 2).collect(Collectors.toList())
Optional.of("Test").map(s -> s.concat(" ").concat(" One")).get()
https://en.wikipedia.org/wiki/Monad_(functional_programming)
Use Case of Optional: Utility method to get
encrypted password in base 64
public String encodePassword1(String password) throws Exception {
return Optional.ofNullable(password)
.map(String::getBytes)
.map(MessageDigest.getInstance("SHA1")::digest)
.map(Base64.getEncoder()::encodeToString)
.orElse(null);
//.orElseThrow(IllegalArgumentException::new);
}
public String encodePassword2(String password) throws Exception{
if (password == null)
return password;
return Base64.encode(MessageDigest.getInstance("SHA1").digest(password.getBytes()));
}
Exercise
• Write a method that accept String (which can be null) and return
number of characters in the String. If null throw
IllegalArgumentException.
Use Cases of Stream: Intro
There many Stream type constructors
• Directly from Stream class
Stream.of(T…t)
• From Collections
List<String> list = new ArrayList<>();
list.stream();
• Primitive Streams
• IntStream
• IntStream interator
IntStream.iterate(1, i -> i++).limit(100) [ for(int i = 0; i < 100; i++) ]
• Random IntStream
ThreadLocalRandom.current().ints()
• LongStream (similar to intstream)
• Buffered Reader
• new BufferedReader(new FileReader("input.txt")).lines();
Use Case of Optional: Find π with random
numbers
long sampleSize = 1_000_000_000L;
long count = ThreadLocalRandom.current().doubles(0,1)
.limit(sampleSize)
.map(d -> Math.pow(d, 2D))
.map(d -> d + Math.pow(ThreadLocalRandom.current().nextDouble(0D,1D), 2D))
.map(Math::sqrt)
.filter(d -> d < 1D)
.count();
System.out.printf("Original: %s Computed: %s %n", Math.PI, 4D * count / sampleSize );
.
.
. .
.
. .
..
.
.
.
.
.
.
.
. .
.
. .
..
.
.
.
.
.
.
.
. .
.
.
..
.
.
.
.
.
.
.
.
.
..
.
.
.
.
.
.
.
..
.
.
.
.
.
.
.
.
.
. . . .
. . ..
.
. ..
.
. . ..
.
. . .
. .
. .
.
.
.
.
.
.
.
..
.
.
.
.
.
.
.
..
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
..
.
.
.
.
.
.
.
..
.
.
.
.
.
.
.
.
.
https://codepen.io/andrewarchi/pen/mRMRed
....
....
....
.
....
.
... ..
..
.
....
....
....
.
....
.
... ..
..
.
Side Note: Using Parallel Stream
StopWatch stopWatch = new StopWatch();
stopWatch.start();
long sampleSize = 1_000_000_000L;
long count = ThreadLocalRandom.current().doubles(0,1)
.limit(sampleSize)
.parallel()
.map(d -> Math.pow(d, 2D))
.map(d -> d + Math.pow(ThreadLocalRandom.current().nextDouble(0D,1D), 2D))
.map(Math::sqrt)
.filter(d -> d < 1D)
.count();
stopWatch.stop();
System.out.printf("Original: %s Computed: %s , Time: %s %n",
Math.PI,
4D * count / sampleSize,
stopWatch);
Side Note: Use of Core
Original: 3.141592653589793 Computed: 3.141606068 , Time: 0:00:04.342
With Parallel Streams
Original: 3.141592653589793 Computed: 3.141551928 , Time: 0:00:38.072
With Serial Streams
Base Line Processes Usage
Exercise
• Read File with one billion numbers and find the Average
https://tinyurl.com/y8k8dfkf
Monad As A Design Pattern
Structural Pattern
• Operation Chaining
• Apply Functions Regardless of the result of any of them
https://github.com/iluwatar/java-design-patterns/tree/master/monad
Try Monad
Optional for NullPointerException, Try For RuntimeException
import java.util.function.Function;
public class Try<I> {
private I i;
private Try(I i) {
this.i = i;
}
// Type Constructor
public static <O> Try<O> of(O instance) {
return new Try<O>(instance);
}
// Bind
public <O> Try<O> attempt(Function<I, O> function) {
try {
O o = function.apply(i);
return new Try<O>(o);
} catch (Throwable t) {
return new Try<O>(null);
}
}
// Return
public I get() {
return i;
}
// Return
public I getOrElse(I defaultValue) {
return i == null ? defaultValue : i;
}
}
Exercise
• Write a monad which uses provided default value if the value is null when
chaining.
String lname = DeafultM.of(user)
.map(User::getName, “Roy”)
.map(s -> lastNameMap.get(s), “James”)
.get();
• Write a monad which uses provided default value if the value is not
provided criteria use when chaining.
String lname = DeafultM.of(user)
.map(User::getName, s -> s.length() < 1, “Roy”)
.map(s -> lastNameMap.get(s), s.contains(“R”), “James”)
.get();
Things to study more
• Monad functions: zip, map, flatmap, sequence
• Monad Design Pattern: https://github.com/iluwatar/java-design-
patterns/tree/master/monad
• Monoids: https://en.wikipedia.org/wiki/Monoid
• Use of Optional: https://www.programcreek.com/java-api-
examples/?api=java.util.Optional
• Functor and Monad Examples in Plain Java.
https://dzone.com/articles/functor-and-monad-examples-in-plain-
java

Weitere ähnliche Inhalte

Was ist angesagt?

Mini-lab 1: Stochastic Gradient Descent classifier, Optimizing Logistic Regre...
Mini-lab 1: Stochastic Gradient Descent classifier, Optimizing Logistic Regre...Mini-lab 1: Stochastic Gradient Descent classifier, Optimizing Logistic Regre...
Mini-lab 1: Stochastic Gradient Descent classifier, Optimizing Logistic Regre...Yao Yao
 
Modern Algorithms and Data Structures - 1. Bloom Filters, Merkle Trees
Modern Algorithms and Data Structures - 1. Bloom Filters, Merkle TreesModern Algorithms and Data Structures - 1. Bloom Filters, Merkle Trees
Modern Algorithms and Data Structures - 1. Bloom Filters, Merkle TreesLorenzo Alberton
 
HyperLogLog in Hive - How to count sheep efficiently?
HyperLogLog in Hive - How to count sheep efficiently?HyperLogLog in Hive - How to count sheep efficiently?
HyperLogLog in Hive - How to count sheep efficiently?bzamecnik
 
Big Data Day LA 2015 - Large Scale Distinct Count -- The HyperLogLog algorith...
Big Data Day LA 2015 - Large Scale Distinct Count -- The HyperLogLog algorith...Big Data Day LA 2015 - Large Scale Distinct Count -- The HyperLogLog algorith...
Big Data Day LA 2015 - Large Scale Distinct Count -- The HyperLogLog algorith...Data Con LA
 
Probabilistic data structures. Part 2. Cardinality
Probabilistic data structures. Part 2. CardinalityProbabilistic data structures. Part 2. Cardinality
Probabilistic data structures. Part 2. CardinalityAndrii Gakhov
 
Michael Häusler – Everyday flink
Michael Häusler – Everyday flinkMichael Häusler – Everyday flink
Michael Häusler – Everyday flinkFlink Forward
 
Monitoring Your ISP Using InfluxDB Cloud and Raspberry Pi
Monitoring Your ISP Using InfluxDB Cloud and Raspberry PiMonitoring Your ISP Using InfluxDB Cloud and Raspberry Pi
Monitoring Your ISP Using InfluxDB Cloud and Raspberry PiInfluxData
 
Flux and InfluxDB 2.0 by Paul Dix
Flux and InfluxDB 2.0 by Paul DixFlux and InfluxDB 2.0 by Paul Dix
Flux and InfluxDB 2.0 by Paul DixInfluxData
 
Spark schema for free with David Szakallas
Spark schema for free with David SzakallasSpark schema for free with David Szakallas
Spark schema for free with David SzakallasDatabricks
 
Collections in .net technology (2160711)
Collections in .net technology (2160711)Collections in .net technology (2160711)
Collections in .net technology (2160711)Janki Shah
 
Python for R Users
Python for R UsersPython for R Users
Python for R UsersAjay Ohri
 
An Introduction to Higher Order Functions in Spark SQL with Herman van Hovell
An Introduction to Higher Order Functions in Spark SQL with Herman van HovellAn Introduction to Higher Order Functions in Spark SQL with Herman van Hovell
An Introduction to Higher Order Functions in Spark SQL with Herman van HovellDatabricks
 
Spark 4th Meetup Londond - Building a Product with Spark
Spark 4th Meetup Londond - Building a Product with SparkSpark 4th Meetup Londond - Building a Product with Spark
Spark 4th Meetup Londond - Building a Product with Sparksamthemonad
 
Javascript Arrays
Javascript ArraysJavascript Arrays
Javascript Arraysshaheenakv
 
Python for R developers and data scientists
Python for R developers and data scientistsPython for R developers and data scientists
Python for R developers and data scientistsLambda Tree
 
Scaling up data science applications
Scaling up data science applicationsScaling up data science applications
Scaling up data science applicationsKexin Xie
 
Stratosphere Intro (Java and Scala Interface)
Stratosphere Intro (Java and Scala Interface)Stratosphere Intro (Java and Scala Interface)
Stratosphere Intro (Java and Scala Interface)Robert Metzger
 
How to Create Database component -Enterprise Application Using C# Lab
How to Create Database component -Enterprise Application Using C# Lab  How to Create Database component -Enterprise Application Using C# Lab
How to Create Database component -Enterprise Application Using C# Lab priya Nithya
 

Was ist angesagt? (20)

Mini-lab 1: Stochastic Gradient Descent classifier, Optimizing Logistic Regre...
Mini-lab 1: Stochastic Gradient Descent classifier, Optimizing Logistic Regre...Mini-lab 1: Stochastic Gradient Descent classifier, Optimizing Logistic Regre...
Mini-lab 1: Stochastic Gradient Descent classifier, Optimizing Logistic Regre...
 
Modern Algorithms and Data Structures - 1. Bloom Filters, Merkle Trees
Modern Algorithms and Data Structures - 1. Bloom Filters, Merkle TreesModern Algorithms and Data Structures - 1. Bloom Filters, Merkle Trees
Modern Algorithms and Data Structures - 1. Bloom Filters, Merkle Trees
 
HyperLogLog in Hive - How to count sheep efficiently?
HyperLogLog in Hive - How to count sheep efficiently?HyperLogLog in Hive - How to count sheep efficiently?
HyperLogLog in Hive - How to count sheep efficiently?
 
Big Data Day LA 2015 - Large Scale Distinct Count -- The HyperLogLog algorith...
Big Data Day LA 2015 - Large Scale Distinct Count -- The HyperLogLog algorith...Big Data Day LA 2015 - Large Scale Distinct Count -- The HyperLogLog algorith...
Big Data Day LA 2015 - Large Scale Distinct Count -- The HyperLogLog algorith...
 
Probabilistic data structures. Part 2. Cardinality
Probabilistic data structures. Part 2. CardinalityProbabilistic data structures. Part 2. Cardinality
Probabilistic data structures. Part 2. Cardinality
 
Michael Häusler – Everyday flink
Michael Häusler – Everyday flinkMichael Häusler – Everyday flink
Michael Häusler – Everyday flink
 
Monitoring Your ISP Using InfluxDB Cloud and Raspberry Pi
Monitoring Your ISP Using InfluxDB Cloud and Raspberry PiMonitoring Your ISP Using InfluxDB Cloud and Raspberry Pi
Monitoring Your ISP Using InfluxDB Cloud and Raspberry Pi
 
Flux and InfluxDB 2.0 by Paul Dix
Flux and InfluxDB 2.0 by Paul DixFlux and InfluxDB 2.0 by Paul Dix
Flux and InfluxDB 2.0 by Paul Dix
 
Spark schema for free with David Szakallas
Spark schema for free with David SzakallasSpark schema for free with David Szakallas
Spark schema for free with David Szakallas
 
Collections in .net technology (2160711)
Collections in .net technology (2160711)Collections in .net technology (2160711)
Collections in .net technology (2160711)
 
Profiling in Python
Profiling in PythonProfiling in Python
Profiling in Python
 
Python for R Users
Python for R UsersPython for R Users
Python for R Users
 
An Introduction to Higher Order Functions in Spark SQL with Herman van Hovell
An Introduction to Higher Order Functions in Spark SQL with Herman van HovellAn Introduction to Higher Order Functions in Spark SQL with Herman van Hovell
An Introduction to Higher Order Functions in Spark SQL with Herman van Hovell
 
Spark 4th Meetup Londond - Building a Product with Spark
Spark 4th Meetup Londond - Building a Product with SparkSpark 4th Meetup Londond - Building a Product with Spark
Spark 4th Meetup Londond - Building a Product with Spark
 
Javascript Arrays
Javascript ArraysJavascript Arrays
Javascript Arrays
 
Python for R developers and data scientists
Python for R developers and data scientistsPython for R developers and data scientists
Python for R developers and data scientists
 
Scaling up data science applications
Scaling up data science applicationsScaling up data science applications
Scaling up data science applications
 
Stratosphere Intro (Java and Scala Interface)
Stratosphere Intro (Java and Scala Interface)Stratosphere Intro (Java and Scala Interface)
Stratosphere Intro (Java and Scala Interface)
 
Enter The Matrix
Enter The MatrixEnter The Matrix
Enter The Matrix
 
How to Create Database component -Enterprise Application Using C# Lab
How to Create Database component -Enterprise Application Using C# Lab  How to Create Database component -Enterprise Application Using C# Lab
How to Create Database component -Enterprise Application Using C# Lab
 

Ähnlich wie Java 8 monads

Wprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
Wprowadzenie do technologii Big Data / Intro to Big Data EcosystemWprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
Wprowadzenie do technologii Big Data / Intro to Big Data EcosystemSages
 
Real-Time Spark: From Interactive Queries to Streaming
Real-Time Spark: From Interactive Queries to StreamingReal-Time Spark: From Interactive Queries to Streaming
Real-Time Spark: From Interactive Queries to StreamingDatabricks
 
Practical data science_public
Practical data science_publicPractical data science_public
Practical data science_publicLong Nguyen
 
Wprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache HadoopWprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache HadoopSages
 
Apache Flink: API, runtime, and project roadmap
Apache Flink: API, runtime, and project roadmapApache Flink: API, runtime, and project roadmap
Apache Flink: API, runtime, and project roadmapKostas Tzoumas
 
Java programming lab manual
Java programming lab manualJava programming lab manual
Java programming lab manualsameer farooq
 
Analyzing On-Chip Interconnect with Modern C++
Analyzing On-Chip Interconnect with Modern C++Analyzing On-Chip Interconnect with Modern C++
Analyzing On-Chip Interconnect with Modern C++Jeff Trull
 
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash courseCodepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash courseSages
 
R programming & Machine Learning
R programming & Machine LearningR programming & Machine Learning
R programming & Machine LearningAmanBhalla14
 
Big Data Analytics with Scala at SCALA.IO 2013
Big Data Analytics with Scala at SCALA.IO 2013Big Data Analytics with Scala at SCALA.IO 2013
Big Data Analytics with Scala at SCALA.IO 2013Samir Bessalah
 
Legacy lambda code
Legacy lambda codeLegacy lambda code
Legacy lambda codePeter Lawrey
 
Chapter 1 Basic Concepts
Chapter 1 Basic ConceptsChapter 1 Basic Concepts
Chapter 1 Basic ConceptsHareem Aslam
 
Kafka Summit NYC 2017 - Easy, Scalable, Fault-tolerant Stream Processing with...
Kafka Summit NYC 2017 - Easy, Scalable, Fault-tolerant Stream Processing with...Kafka Summit NYC 2017 - Easy, Scalable, Fault-tolerant Stream Processing with...
Kafka Summit NYC 2017 - Easy, Scalable, Fault-tolerant Stream Processing with...confluent
 
Story of static code analyzer development
Story of static code analyzer developmentStory of static code analyzer development
Story of static code analyzer developmentAndrey Karpov
 
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...GeeksLab Odessa
 

Ähnlich wie Java 8 monads (20)

Wprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
Wprowadzenie do technologii Big Data / Intro to Big Data EcosystemWprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
Wprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
 
Real-Time Spark: From Interactive Queries to Streaming
Real-Time Spark: From Interactive Queries to StreamingReal-Time Spark: From Interactive Queries to Streaming
Real-Time Spark: From Interactive Queries to Streaming
 
R Language Introduction
R Language IntroductionR Language Introduction
R Language Introduction
 
Practical data science_public
Practical data science_publicPractical data science_public
Practical data science_public
 
Anti patterns
Anti patternsAnti patterns
Anti patterns
 
Wprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache HadoopWprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache Hadoop
 
Apache Flink: API, runtime, and project roadmap
Apache Flink: API, runtime, and project roadmapApache Flink: API, runtime, and project roadmap
Apache Flink: API, runtime, and project roadmap
 
Java programming lab manual
Java programming lab manualJava programming lab manual
Java programming lab manual
 
Analyzing On-Chip Interconnect with Modern C++
Analyzing On-Chip Interconnect with Modern C++Analyzing On-Chip Interconnect with Modern C++
Analyzing On-Chip Interconnect with Modern C++
 
Spark workshop
Spark workshopSpark workshop
Spark workshop
 
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash courseCodepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
 
Lambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter LawreyLambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter Lawrey
 
R programming & Machine Learning
R programming & Machine LearningR programming & Machine Learning
R programming & Machine Learning
 
Big Data Analytics with Scala at SCALA.IO 2013
Big Data Analytics with Scala at SCALA.IO 2013Big Data Analytics with Scala at SCALA.IO 2013
Big Data Analytics with Scala at SCALA.IO 2013
 
Legacy lambda code
Legacy lambda codeLegacy lambda code
Legacy lambda code
 
Functional Programming
Functional ProgrammingFunctional Programming
Functional Programming
 
Chapter 1 Basic Concepts
Chapter 1 Basic ConceptsChapter 1 Basic Concepts
Chapter 1 Basic Concepts
 
Kafka Summit NYC 2017 - Easy, Scalable, Fault-tolerant Stream Processing with...
Kafka Summit NYC 2017 - Easy, Scalable, Fault-tolerant Stream Processing with...Kafka Summit NYC 2017 - Easy, Scalable, Fault-tolerant Stream Processing with...
Kafka Summit NYC 2017 - Easy, Scalable, Fault-tolerant Stream Processing with...
 
Story of static code analyzer development
Story of static code analyzer developmentStory of static code analyzer development
Story of static code analyzer development
 
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
 

Kürzlich hochgeladen

HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456KiaraTiradoMicha
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
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
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfVishalKumarJha10
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...Shane Coughlan
 
%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
 
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
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
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
 
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
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedDelhi Call girls
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 

Kürzlich hochgeladen (20)

HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
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...
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
%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
 
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
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
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
 
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
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 

Java 8 monads

  • 1. Java 8 : Monads
  • 2. Generics: Have Typed Containers List list = new ArrayList(); list.add("one"); list.add(1); list.add(1L); list.add(new Object()); Before After List<String> list = new ArrayList<>(); list.add("one"); list.add("1"); list.add(“1212”); Typed ContainerContainer
  • 3. A Thing we cannot do with containers Transform container of String to a container of Integers
  • 4. Monad: {Type Constructor, Bind, Return} Optional Stream Type Constructor of of Bind map map Return get collect Example: Stream.of(1,2,3,4,5).map(i -> i + 2).collect(Collectors.toList()) Optional.of("Test").map(s -> s.concat(" ").concat(" One")).get() https://en.wikipedia.org/wiki/Monad_(functional_programming)
  • 5. Use Case of Optional: Utility method to get encrypted password in base 64 public String encodePassword1(String password) throws Exception { return Optional.ofNullable(password) .map(String::getBytes) .map(MessageDigest.getInstance("SHA1")::digest) .map(Base64.getEncoder()::encodeToString) .orElse(null); //.orElseThrow(IllegalArgumentException::new); } public String encodePassword2(String password) throws Exception{ if (password == null) return password; return Base64.encode(MessageDigest.getInstance("SHA1").digest(password.getBytes())); }
  • 6. Exercise • Write a method that accept String (which can be null) and return number of characters in the String. If null throw IllegalArgumentException.
  • 7. Use Cases of Stream: Intro There many Stream type constructors • Directly from Stream class Stream.of(T…t) • From Collections List<String> list = new ArrayList<>(); list.stream(); • Primitive Streams • IntStream • IntStream interator IntStream.iterate(1, i -> i++).limit(100) [ for(int i = 0; i < 100; i++) ] • Random IntStream ThreadLocalRandom.current().ints() • LongStream (similar to intstream) • Buffered Reader • new BufferedReader(new FileReader("input.txt")).lines();
  • 8. Use Case of Optional: Find π with random numbers long sampleSize = 1_000_000_000L; long count = ThreadLocalRandom.current().doubles(0,1) .limit(sampleSize) .map(d -> Math.pow(d, 2D)) .map(d -> d + Math.pow(ThreadLocalRandom.current().nextDouble(0D,1D), 2D)) .map(Math::sqrt) .filter(d -> d < 1D) .count(); System.out.printf("Original: %s Computed: %s %n", Math.PI, 4D * count / sampleSize ); . . . . . . . .. . . . . . . . . . . . . .. . . . . . . . . . . . .. . . . . . . . . . .. . . . . . . . .. . . . . . . . . . . . . . . . .. . . .. . . . .. . . . . . . . . . . . . . . . .. . . . . . . . .. . . . . . . . . . . . . . . . .. . . . . . . . .. . . . . . . . . . https://codepen.io/andrewarchi/pen/mRMRed .... .... .... . .... . ... .. .. . .... .... .... . .... . ... .. .. .
  • 9. Side Note: Using Parallel Stream StopWatch stopWatch = new StopWatch(); stopWatch.start(); long sampleSize = 1_000_000_000L; long count = ThreadLocalRandom.current().doubles(0,1) .limit(sampleSize) .parallel() .map(d -> Math.pow(d, 2D)) .map(d -> d + Math.pow(ThreadLocalRandom.current().nextDouble(0D,1D), 2D)) .map(Math::sqrt) .filter(d -> d < 1D) .count(); stopWatch.stop(); System.out.printf("Original: %s Computed: %s , Time: %s %n", Math.PI, 4D * count / sampleSize, stopWatch);
  • 10. Side Note: Use of Core Original: 3.141592653589793 Computed: 3.141606068 , Time: 0:00:04.342 With Parallel Streams Original: 3.141592653589793 Computed: 3.141551928 , Time: 0:00:38.072 With Serial Streams Base Line Processes Usage
  • 11. Exercise • Read File with one billion numbers and find the Average https://tinyurl.com/y8k8dfkf
  • 12. Monad As A Design Pattern Structural Pattern • Operation Chaining • Apply Functions Regardless of the result of any of them https://github.com/iluwatar/java-design-patterns/tree/master/monad
  • 13. Try Monad Optional for NullPointerException, Try For RuntimeException import java.util.function.Function; public class Try<I> { private I i; private Try(I i) { this.i = i; } // Type Constructor public static <O> Try<O> of(O instance) { return new Try<O>(instance); } // Bind public <O> Try<O> attempt(Function<I, O> function) { try { O o = function.apply(i); return new Try<O>(o); } catch (Throwable t) { return new Try<O>(null); } } // Return public I get() { return i; } // Return public I getOrElse(I defaultValue) { return i == null ? defaultValue : i; } }
  • 14. Exercise • Write a monad which uses provided default value if the value is null when chaining. String lname = DeafultM.of(user) .map(User::getName, “Roy”) .map(s -> lastNameMap.get(s), “James”) .get(); • Write a monad which uses provided default value if the value is not provided criteria use when chaining. String lname = DeafultM.of(user) .map(User::getName, s -> s.length() < 1, “Roy”) .map(s -> lastNameMap.get(s), s.contains(“R”), “James”) .get();
  • 15. Things to study more • Monad functions: zip, map, flatmap, sequence • Monad Design Pattern: https://github.com/iluwatar/java-design- patterns/tree/master/monad • Monoids: https://en.wikipedia.org/wiki/Monoid • Use of Optional: https://www.programcreek.com/java-api- examples/?api=java.util.Optional • Functor and Monad Examples in Plain Java. https://dzone.com/articles/functor-and-monad-examples-in-plain- java