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

More Related Content

What's hot

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 Trees
Lorenzo 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. Cardinality
Andrii Gakhov
 
Michael Häusler – Everyday flink
Michael Häusler – Everyday flinkMichael Häusler – Everyday flink
Michael Häusler – Everyday flink
Flink 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 Pi
InfluxData
 
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
InfluxData
 
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
Databricks
 
Collections in .net technology (2160711)
Collections in .net technology (2160711)Collections in .net technology (2160711)
Collections in .net technology (2160711)
Janki Shah
 
Profiling in Python
Profiling in PythonProfiling in Python
Profiling in Python
Fabian Pedregosa
 
Python for R Users
Python for R UsersPython for R Users
Python for R Users
Ajay 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 Hovell
Databricks
 
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
samthemonad
 
Javascript Arrays
Javascript ArraysJavascript Arrays
Javascript Arrays
shaheenakv
 
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
Lambda Tree
 
Scaling up data science applications
Scaling up data science applicationsScaling up data science applications
Scaling up data science applications
Kexin 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
 
Enter The Matrix
Enter The MatrixEnter The Matrix
Enter The Matrix
Mike Anderson
 
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
 

What's hot (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
 

Similar to 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 Ecosystem
Sages
 
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
Databricks
 
R Language Introduction
R Language IntroductionR Language Introduction
R Language Introduction
Khaled Al-Shamaa
 
Practical data science_public
Practical data science_publicPractical data science_public
Practical data science_public
Long Nguyen
 
Anti patterns
Anti patternsAnti patterns
Anti patterns
Alex Tumanoff
 
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
Sages
 
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
Kostas Tzoumas
 
Java programming lab manual
Java programming lab manualJava programming lab manual
Java programming lab manual
sameer 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
 
Spark workshop
Spark workshopSpark workshop
Spark workshop
Wojciech Pituła
 
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
Sages
 
Lambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter LawreyLambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter Lawrey
JAXLondon_Conference
 
R programming & Machine Learning
R programming & Machine LearningR programming & Machine Learning
R programming & Machine Learning
AmanBhalla14
 
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
Samir Bessalah
 
Legacy lambda code
Legacy lambda codeLegacy lambda code
Legacy lambda code
Peter Lawrey
 
Functional Programming
Functional ProgrammingFunctional Programming
Functional Programming
Olexandra Dmytrenko
 
Chapter 1 Basic Concepts
Chapter 1 Basic ConceptsChapter 1 Basic Concepts
Chapter 1 Basic Concepts
Hareem 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 development
Andrey Karpov
 
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
GeeksLab Odessa
 

Similar to 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: Алгебра для реактивного пр...
 

Recently uploaded

Orca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container OrchestrationOrca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container Orchestration
Pedro J. Molina
 
TheFutureIsDynamic-BoxLang-CFCamp2024.pdf
TheFutureIsDynamic-BoxLang-CFCamp2024.pdfTheFutureIsDynamic-BoxLang-CFCamp2024.pdf
TheFutureIsDynamic-BoxLang-CFCamp2024.pdf
Ortus Solutions, Corp
 
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
gapen1
 
Boost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management AppsBoost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management Apps
Jhone kinadey
 
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdfBaha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid
 
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
safelyiotech
 
The Role of DevOps in Digital Transformation.pdf
The Role of DevOps in Digital Transformation.pdfThe Role of DevOps in Digital Transformation.pdf
The Role of DevOps in Digital Transformation.pdf
mohitd6
 
Computer Science & Engineering VI Sem- New Syllabus.pdf
Computer Science & Engineering VI Sem- New Syllabus.pdfComputer Science & Engineering VI Sem- New Syllabus.pdf
Computer Science & Engineering VI Sem- New Syllabus.pdf
chandangoswami40933
 
Ensuring Efficiency and Speed with Practical Solutions for Clinical Operations
Ensuring Efficiency and Speed with Practical Solutions for Clinical OperationsEnsuring Efficiency and Speed with Practical Solutions for Clinical Operations
Ensuring Efficiency and Speed with Practical Solutions for Clinical Operations
OnePlan Solutions
 
Streamlining End-to-End Testing Automation
Streamlining End-to-End Testing AutomationStreamlining End-to-End Testing Automation
Streamlining End-to-End Testing Automation
Anand Bagmar
 
Beginner's Guide to Observability@Devoxx PL 2024
Beginner's  Guide to Observability@Devoxx PL 2024Beginner's  Guide to Observability@Devoxx PL 2024
Beginner's Guide to Observability@Devoxx PL 2024
michniczscribd
 
14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
ShulagnaSarkar2
 
Microsoft-Power-Platform-Adoption-Planning.pptx
Microsoft-Power-Platform-Adoption-Planning.pptxMicrosoft-Power-Platform-Adoption-Planning.pptx
Microsoft-Power-Platform-Adoption-Planning.pptx
jrodriguezq3110
 
What’s New in VictoriaLogs - Q2 2024 Update
What’s New in VictoriaLogs - Q2 2024 UpdateWhat’s New in VictoriaLogs - Q2 2024 Update
What’s New in VictoriaLogs - Q2 2024 Update
VictoriaMetrics
 
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data PlatformAlluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio, Inc.
 
Strengthening Web Development with CommandBox 6: Seamless Transition and Scal...
Strengthening Web Development with CommandBox 6: Seamless Transition and Scal...Strengthening Web Development with CommandBox 6: Seamless Transition and Scal...
Strengthening Web Development with CommandBox 6: Seamless Transition and Scal...
Ortus Solutions, Corp
 
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptxOperational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
sandeepmenon62
 
ppt on the brain chip neuralink.pptx
ppt  on   the brain  chip neuralink.pptxppt  on   the brain  chip neuralink.pptx
ppt on the brain chip neuralink.pptx
Reetu63
 
Building API data products on top of your real-time data infrastructure
Building API data products on top of your real-time data infrastructureBuilding API data products on top of your real-time data infrastructure
Building API data products on top of your real-time data infrastructure
confluent
 

Recently uploaded (20)

Orca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container OrchestrationOrca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container Orchestration
 
TheFutureIsDynamic-BoxLang-CFCamp2024.pdf
TheFutureIsDynamic-BoxLang-CFCamp2024.pdfTheFutureIsDynamic-BoxLang-CFCamp2024.pdf
TheFutureIsDynamic-BoxLang-CFCamp2024.pdf
 
bgiolcb
bgiolcbbgiolcb
bgiolcb
 
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
 
Boost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management AppsBoost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management Apps
 
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdfBaha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
 
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
 
The Role of DevOps in Digital Transformation.pdf
The Role of DevOps in Digital Transformation.pdfThe Role of DevOps in Digital Transformation.pdf
The Role of DevOps in Digital Transformation.pdf
 
Computer Science & Engineering VI Sem- New Syllabus.pdf
Computer Science & Engineering VI Sem- New Syllabus.pdfComputer Science & Engineering VI Sem- New Syllabus.pdf
Computer Science & Engineering VI Sem- New Syllabus.pdf
 
Ensuring Efficiency and Speed with Practical Solutions for Clinical Operations
Ensuring Efficiency and Speed with Practical Solutions for Clinical OperationsEnsuring Efficiency and Speed with Practical Solutions for Clinical Operations
Ensuring Efficiency and Speed with Practical Solutions for Clinical Operations
 
Streamlining End-to-End Testing Automation
Streamlining End-to-End Testing AutomationStreamlining End-to-End Testing Automation
Streamlining End-to-End Testing Automation
 
Beginner's Guide to Observability@Devoxx PL 2024
Beginner's  Guide to Observability@Devoxx PL 2024Beginner's  Guide to Observability@Devoxx PL 2024
Beginner's Guide to Observability@Devoxx PL 2024
 
14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
 
Microsoft-Power-Platform-Adoption-Planning.pptx
Microsoft-Power-Platform-Adoption-Planning.pptxMicrosoft-Power-Platform-Adoption-Planning.pptx
Microsoft-Power-Platform-Adoption-Planning.pptx
 
What’s New in VictoriaLogs - Q2 2024 Update
What’s New in VictoriaLogs - Q2 2024 UpdateWhat’s New in VictoriaLogs - Q2 2024 Update
What’s New in VictoriaLogs - Q2 2024 Update
 
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data PlatformAlluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
 
Strengthening Web Development with CommandBox 6: Seamless Transition and Scal...
Strengthening Web Development with CommandBox 6: Seamless Transition and Scal...Strengthening Web Development with CommandBox 6: Seamless Transition and Scal...
Strengthening Web Development with CommandBox 6: Seamless Transition and Scal...
 
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptxOperational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
 
ppt on the brain chip neuralink.pptx
ppt  on   the brain  chip neuralink.pptxppt  on   the brain  chip neuralink.pptx
ppt on the brain chip neuralink.pptx
 
Building API data products on top of your real-time data infrastructure
Building API data products on top of your real-time data infrastructureBuilding API data products on top of your real-time data infrastructure
Building API data products on top of your real-time data infrastructure
 

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