SlideShare a Scribd company logo
09 Sept 2015
Functional Programming in Java
Jim Bethancourt
@jimbethancourt
1
1 What is Functional Programming?
2 What are the Benefits?
3 Functions
4 Lambdas
5 Streams
6 Terminal Operators
7 Intermediate Operators
8 Collectors
9 Optional
Agenda
2
What is Functional Programming?
Functions have no state
They don’t change
• the world around them
• their input
• access global state
Given the same input, they produce the same output
Just like a function in math: f(x) = y
What is Functional Programming
3
What is Functional Programming?
Let’s face it – Computer application codebases have gotten HUGE!
How big are the codebases you work on?
Mutable state is frequently difficult to manage
Have you forgotten to set a flag too?
Imperative style code is often difficult to read
Don’t tell me what you’re doing – just do it!
Why Functional Programming?
4
1 What is Functional Programming?
2 What are the Benefits?
3 Functions
4 Lambdas
5 Streams
6 Terminal Operators
7 Intermediate Operators
8 Collectors
9 Optional
5
What are the Benefits?
Functional Programs are easier to:
• Scale
• Read
• Test
Faster!
6
1 What is Functional Programming?
2 What are the Benefits?
3 Functions
4 Lambdas
5 Streams
6 Terminal Operators
7 Intermediate Operators
8 Collectors
9 Optional
7
Functions
Functions are first-class citizens:
• They can be assigned, passed, and returned
just like variables!
• They don’t mutate state, they transform values
• Treating functions as values is known as First-
class Functions or Higher-order Programming
Functions as First-Class Citizens
8
Functions
Functions are isolated
But what if I want secondary output / side
effects?
Use a Consumer<T>!
Functions Are Isolated
9
Functions
public void convertTemps() {
DoubleUnaryOperator convertFtoC =
expandedCurriedConverter(-32, 5.0/9, 0);
S.o.p(convertFtoC.applyAsDouble(98.6));
}
static DoubleUnaryOperator
expandedCurriedConverter(double w, double y, double z) {
return (double x) -> (x + w) * y + z;
}
Example of Functional Programming
10
Functions
Imperative vs Declarative
Imperative
How
Mutate
Side-effects
Pass objects
Hard to compose
Declarative
What
Transform
Pure
Pass functions too
Functional composition
11
1 What is Functional Programming?
2 What are the Benefits?
3 Functions
4 Lambdas
5 Streams
6 Terminal Operators
7 Intermediate Operators
8 Collectors
9 Optional
12
Lambdas
A lambda is an inline functional definition
They can see and use nearby values, but can’t
change them
Closures can change nearby variables.
Java 8 lambdas are NOT closures since they
require all variables to be final
What are Lambdas
13
Lambdas
Before:
Comparator<Apple> byWeight = new Comparator<Apple>() {
public int compare(Apple a1, Apple a2){
return a1.getWeight().compareTo(a2.getWeight());
}
};
After (with lambda expressions):
Comparator<Apple> byWeight =
(Apple a1, Apple a2) -> a1.getWeight().compareTo(a2.getWeight());
Before and After Lambdas
14
1 What is Functional Programming?
2 What are the Benefits?
3 Functions
4 Lambdas
5 Streams
6 Terminal Operators
7 Intermediate Operators
8 Collectors
9 Optional
15
Streams
A sequence of elements supporting sequential and
parallel aggregate operations. (from Java 8 Javadoc)
Streams allow for you to manipulate collections of data
in a declarative way.
Operations can be chained together to form an
expressive processing pipeline
Streams perform internal iteration behind the scenes,
allowing you to focus on what rather than how
Streams can easily be parallelized by calling
parallelStream() -- YMMV
What is a Stream?
16
Streams
Each intermediate operation performed on a stream returns another stream
This allows for any number of intermediate operations to be performed on a stream of elements
These operations include but are not limited to
filter()
map()
flatMap()
distinct()
Streams don’t perform an evaluation until they reach their terminal operation is reached, such as
reduce()
collect()
sum(), max(), min(), etc.
Streams Return Streams, and they’re Lazy!!!
17
1 What is Functional Programming?
2 What are the Benefits?
3 Functions
4 Lambdas
5 Streams
6 Terminal Operators
7 Intermediate Operators
8 Collectors
9 Optional
18
Terminal Operators
Terminal operators trigger processing and return a
value. reduce(), count(), anyMatch(), and
summaryStatistics() are examples of terminal
operations
Once a terminal operation takes place, that instance of
the stream is dead and no longer usable, and no further
processing can take place on it.
The End is Coming!
19
Terminal Operators
Streams can only be traversed once, so how can we
reuse the code we wrote?
Assign the nonterminated stream operation to a stream
supplier object!
Supplier<Stream<String>> streamSupplier =
() -> Stream.of("d2", "a2", "b1", "b3", "c")
.filter(s -> s.startsWith("a"));
streamSupplier.get().anyMatch(s -> true); // ok
streamSupplier.get().noneMatch(s -> true); // ok
One Time Traversal and Stream Reuse
20
1 What is Functional Programming?
2 What are the Benefits?
3 Functions
4 Lambdas
5 Streams
6 Terminal Operators
7 Intermediate Operators
8 Collectors
9 Optional
21
Intermediate Operators
Intermediate Operators perform mapping / transforming and filtering operations on a stream of
elements.
Any number of intermediate operations can be performed on a stream of elements.
people.stream()
.filter(person -> person.getGender() == Gender.MALE)
.map(person -> new Person(person.getName().toUpperCase(), person.getGender(), person.getAge()))
.forEach(System.out::println);
Transforming! More Than Meets the Eye!
22
1 What is Functional Programming?
2 What are the Benefits?
3 Functions
4 Lambdas
5 Streams
6 Terminal Operators
7 Intermediate Operators
8 Collectors
9 Optional
23
Collectors
Collectors allow for objects to be accumulated to be
passed back to a result container such as a Collection or a
Map
Transformations may take place once all elements are
accumulated, but this is not required.
Collector<Employee, ?, Map<Department, Integer>>
summingSalariesByDept =
Collectors.groupingBy(Employee::getDepartment,
summingSalaries);
Finishing the Stream
24
Collectors
Collectors require 3 things:
Empty instance of the output type
Operator that can put an element into that output type
Operation that can combine two of the output type
Collectors within collectors are possible too!
Requirements of Collectors
25
1 What is Functional Programming?
2 What are the Benefits?
3 Functions
4 Lambdas
5 Streams
6 Terminal Operators
7 Intermediate Operators
8 Collectors
9 Optional
26
Optional
Getting Tired?
27
Optional
I’m tired of NPEs!
28
Optional
Instead of returning a null object, return an Optional!
Use Optional as a Safe Return Type
29
Optional
public class Person {
private Optional<Car> car;
public Optional<Car> getCar() { return car; }
}
public class Car {
private Optional<Insurance> insurance;
public Optional<Insurance> getInsurance() { return insurance; }
}
public class Insurance {
private String name;
public String getName() { return name; }
}
Putting Optional to Work
30
Optional
Empty optional creation
Optional<Car> optCar = Optional.empty();
Optional from a non-null value
Optional<Car> optCar = Optional.of(car);
Optional from a possibly null value
Optional<Car> optCar = Optional.ofNullable(car);
Creating Optionals
31
Optional
Optional<Insurance> optInsurance =
Optional.ofNullable(insurance);
Optional<String> name =
optInsurance.map(Insurance::getName);
Getting values in Optionals
32
Optional
This won’t compile!
Optional<Person> optPerson = Optional.of(person);
Optional<String> name =
optPerson.map(Person::getCar)
.map(Car::getInsurance)
.map(Insurance::getName);
Chaining Operations with Optionals
33
Optional
Instead, use flatMap()
public String getCarInsuranceName(Optional<Person> person) {
return person.flatMap(Person::getCar)
.flatMap(Car::getInsurance)
.map(Insurance::getName)
.orElse("Unknown");
}
Chaining Operations with Optionals

More Related Content

What's hot

Intro to JavaScript - Week 2: Function
Intro to JavaScript - Week 2: FunctionIntro to JavaScript - Week 2: Function
Intro to JavaScript - Week 2: Function
Jeongbae Oh
 
Java 8
Java 8Java 8
Java 8
vilniusjug
 
Scilab vs matlab
Scilab vs matlabScilab vs matlab
Scilab vs matlab
Dadan Bagenda
 
Inline functions
Inline functionsInline functions
Inline functions
DhwaniHingorani
 
Verilog Tasks and functions
Verilog Tasks and functionsVerilog Tasks and functions
Verilog Tasks and functions
Vinchipsytm Vlsitraining
 
Inline function
Inline functionInline function
Inline function
Tech_MX
 
Java8 training - class 3
Java8 training - class 3Java8 training - class 3
Java8 training - class 3
Marut Singh
 
Understanding Implicits in Scala
Understanding Implicits in ScalaUnderstanding Implicits in Scala
Understanding Implicits in Scala
datamantra
 
Java8 training - Class 1
Java8 training  - Class 1Java8 training  - Class 1
Java8 training - Class 1
Marut Singh
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
Garima Singh Makhija
 
#OOP_D_ITS - 5th - C++ Oop Operator Overloading
#OOP_D_ITS - 5th - C++ Oop Operator Overloading#OOP_D_ITS - 5th - C++ Oop Operator Overloading
#OOP_D_ITS - 5th - C++ Oop Operator Overloading
Hadziq Fabroyir
 
Introduction to RxJava on Android
Introduction to RxJava on AndroidIntroduction to RxJava on Android
Introduction to RxJava on Android
Chris Arriola
 
TMPA-2017: Evolutionary Algorithms in Test Generation for digital systems
TMPA-2017: Evolutionary Algorithms in Test Generation for digital systemsTMPA-2017: Evolutionary Algorithms in Test Generation for digital systems
TMPA-2017: Evolutionary Algorithms in Test Generation for digital systems
Iosif Itkin
 
Enterprise State Management with NGRX/platform
Enterprise State Management with NGRX/platformEnterprise State Management with NGRX/platform
Enterprise State Management with NGRX/platform
Ilia Idakiev
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
ArunaDevi63
 
FRP
FRPFRP
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project Lambda
Rahman USTA
 
TMPA-2017: Simple Type Based Alias Analysis for a VLIW Processor
TMPA-2017: Simple Type Based Alias Analysis for a VLIW ProcessorTMPA-2017: Simple Type Based Alias Analysis for a VLIW Processor
TMPA-2017: Simple Type Based Alias Analysis for a VLIW Processor
Iosif Itkin
 
09 implementing+subprograms
09 implementing+subprograms09 implementing+subprograms
09 implementing+subprograms
baran19901990
 
Function in C Programming
Function in C ProgrammingFunction in C Programming
Function in C Programming
Anil Pokhrel
 

What's hot (20)

Intro to JavaScript - Week 2: Function
Intro to JavaScript - Week 2: FunctionIntro to JavaScript - Week 2: Function
Intro to JavaScript - Week 2: Function
 
Java 8
Java 8Java 8
Java 8
 
Scilab vs matlab
Scilab vs matlabScilab vs matlab
Scilab vs matlab
 
Inline functions
Inline functionsInline functions
Inline functions
 
Verilog Tasks and functions
Verilog Tasks and functionsVerilog Tasks and functions
Verilog Tasks and functions
 
Inline function
Inline functionInline function
Inline function
 
Java8 training - class 3
Java8 training - class 3Java8 training - class 3
Java8 training - class 3
 
Understanding Implicits in Scala
Understanding Implicits in ScalaUnderstanding Implicits in Scala
Understanding Implicits in Scala
 
Java8 training - Class 1
Java8 training  - Class 1Java8 training  - Class 1
Java8 training - Class 1
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
#OOP_D_ITS - 5th - C++ Oop Operator Overloading
#OOP_D_ITS - 5th - C++ Oop Operator Overloading#OOP_D_ITS - 5th - C++ Oop Operator Overloading
#OOP_D_ITS - 5th - C++ Oop Operator Overloading
 
Introduction to RxJava on Android
Introduction to RxJava on AndroidIntroduction to RxJava on Android
Introduction to RxJava on Android
 
TMPA-2017: Evolutionary Algorithms in Test Generation for digital systems
TMPA-2017: Evolutionary Algorithms in Test Generation for digital systemsTMPA-2017: Evolutionary Algorithms in Test Generation for digital systems
TMPA-2017: Evolutionary Algorithms in Test Generation for digital systems
 
Enterprise State Management with NGRX/platform
Enterprise State Management with NGRX/platformEnterprise State Management with NGRX/platform
Enterprise State Management with NGRX/platform
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
FRP
FRPFRP
FRP
 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project Lambda
 
TMPA-2017: Simple Type Based Alias Analysis for a VLIW Processor
TMPA-2017: Simple Type Based Alias Analysis for a VLIW ProcessorTMPA-2017: Simple Type Based Alias Analysis for a VLIW Processor
TMPA-2017: Simple Type Based Alias Analysis for a VLIW Processor
 
09 implementing+subprograms
09 implementing+subprograms09 implementing+subprograms
09 implementing+subprograms
 
Function in C Programming
Function in C ProgrammingFunction in C Programming
Function in C Programming
 

Similar to Functional Programming in Java

Functional programming
Functional programmingFunctional programming
Functional programming
Lhouceine OUHAMZA
 
Booting into functional programming
Booting into functional programmingBooting into functional programming
Booting into functional programming
Dhaval Dalal
 
What`s New in Java 8
What`s New in Java 8What`s New in Java 8
What`s New in Java 8
Mohsen Zainalpour
 
Java 8 streams
Java 8 streams Java 8 streams
Java 8 streams
Srinivasan Raghvan
 
JDK8 Functional API
JDK8 Functional APIJDK8 Functional API
JDK8 Functional API
Justin Lin
 
Java 8 - functional features
Java 8 - functional featuresJava 8 - functional features
Java 8 - functional features
Rafal Rybacki
 
Java 8 - An Overview
Java 8 - An OverviewJava 8 - An Overview
Java 8 - An Overview
Indrajit Das
 
Java8
Java8Java8
cb streams - gavin pickin
cb streams - gavin pickincb streams - gavin pickin
cb streams - gavin pickin
Ortus Solutions, Corp
 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 iti
Ahmed mar3y
 
Streams in Java 8
Streams in Java 8Streams in Java 8
Streams in Java 8
Tobias Coetzee
 
Functional Programming in Java
Functional Programming in JavaFunctional Programming in Java
Functional Programming in Java
Narendran Solai Sridharan
 
Java8
Java8Java8
Functions
FunctionsFunctions
java8
java8java8
Hadoop job chaining
Hadoop job chainingHadoop job chaining
Hadoop job chaining
Subhas Kumar Ghosh
 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
Manav Prasad
 
Java SE 8 library design
Java SE 8 library designJava SE 8 library design
Java SE 8 library design
Stephen Colebourne
 
Matlab for diploma students(1)
Matlab for diploma students(1)Matlab for diploma students(1)
Matlab for diploma students(1)
Retheesh Raj
 
An Introduction to the SOLID Principles
An Introduction to the SOLID PrinciplesAn Introduction to the SOLID Principles
An Introduction to the SOLID Principles
Attila Bertók
 

Similar to Functional Programming in Java (20)

Functional programming
Functional programmingFunctional programming
Functional programming
 
Booting into functional programming
Booting into functional programmingBooting into functional programming
Booting into functional programming
 
What`s New in Java 8
What`s New in Java 8What`s New in Java 8
What`s New in Java 8
 
Java 8 streams
Java 8 streams Java 8 streams
Java 8 streams
 
JDK8 Functional API
JDK8 Functional APIJDK8 Functional API
JDK8 Functional API
 
Java 8 - functional features
Java 8 - functional featuresJava 8 - functional features
Java 8 - functional features
 
Java 8 - An Overview
Java 8 - An OverviewJava 8 - An Overview
Java 8 - An Overview
 
Java8
Java8Java8
Java8
 
cb streams - gavin pickin
cb streams - gavin pickincb streams - gavin pickin
cb streams - gavin pickin
 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 iti
 
Streams in Java 8
Streams in Java 8Streams in Java 8
Streams in Java 8
 
Functional Programming in Java
Functional Programming in JavaFunctional Programming in Java
Functional Programming in Java
 
Java8
Java8Java8
Java8
 
Functions
FunctionsFunctions
Functions
 
java8
java8java8
java8
 
Hadoop job chaining
Hadoop job chainingHadoop job chaining
Hadoop job chaining
 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
 
Java SE 8 library design
Java SE 8 library designJava SE 8 library design
Java SE 8 library design
 
Matlab for diploma students(1)
Matlab for diploma students(1)Matlab for diploma students(1)
Matlab for diploma students(1)
 
An Introduction to the SOLID Principles
An Introduction to the SOLID PrinciplesAn Introduction to the SOLID Principles
An Introduction to the SOLID Principles
 

More from Jim Bethancourt

JavaOne 2011 Recap
JavaOne 2011 RecapJavaOne 2011 Recap
JavaOne 2011 Recap
Jim Bethancourt
 
Ready, Set, Refactor
Ready, Set, RefactorReady, Set, Refactor
Ready, Set, Refactor
Jim Bethancourt
 
Java 8 Feature Preview
Java 8 Feature PreviewJava 8 Feature Preview
Java 8 Feature Preview
Jim Bethancourt
 
Introduction to CDI
Introduction to CDIIntroduction to CDI
Introduction to CDI
Jim Bethancourt
 
Young Java Champions
Young Java ChampionsYoung Java Champions
Young Java Champions
Jim Bethancourt
 
Migrating to Maven 2 Demystified
Migrating to Maven 2 DemystifiedMigrating to Maven 2 Demystified
Migrating to Maven 2 Demystified
Jim Bethancourt
 
User Group Leader Lunch
User Group Leader LunchUser Group Leader Lunch
User Group Leader Lunch
Jim Bethancourt
 
Hearthstone To The Limit
Hearthstone To The LimitHearthstone To The Limit
Hearthstone To The Limit
Jim Bethancourt
 
Recognize, assess, reduce, and manage technical debt
Recognize, assess, reduce, and manage technical debtRecognize, assess, reduce, and manage technical debt
Recognize, assess, reduce, and manage technical debt
Jim Bethancourt
 
Atlassian Bamboo Feature Overview
Atlassian Bamboo Feature OverviewAtlassian Bamboo Feature Overview
Atlassian Bamboo Feature Overview
Jim Bethancourt
 
Java Performance Tweaks
Java Performance TweaksJava Performance Tweaks
Java Performance Tweaks
Jim Bethancourt
 
Refactor to the Limit!
Refactor to the Limit!Refactor to the Limit!
Refactor to the Limit!
Jim Bethancourt
 
Lambdas and Laughs
Lambdas and LaughsLambdas and Laughs
Lambdas and Laughs
Jim Bethancourt
 

More from Jim Bethancourt (13)

JavaOne 2011 Recap
JavaOne 2011 RecapJavaOne 2011 Recap
JavaOne 2011 Recap
 
Ready, Set, Refactor
Ready, Set, RefactorReady, Set, Refactor
Ready, Set, Refactor
 
Java 8 Feature Preview
Java 8 Feature PreviewJava 8 Feature Preview
Java 8 Feature Preview
 
Introduction to CDI
Introduction to CDIIntroduction to CDI
Introduction to CDI
 
Young Java Champions
Young Java ChampionsYoung Java Champions
Young Java Champions
 
Migrating to Maven 2 Demystified
Migrating to Maven 2 DemystifiedMigrating to Maven 2 Demystified
Migrating to Maven 2 Demystified
 
User Group Leader Lunch
User Group Leader LunchUser Group Leader Lunch
User Group Leader Lunch
 
Hearthstone To The Limit
Hearthstone To The LimitHearthstone To The Limit
Hearthstone To The Limit
 
Recognize, assess, reduce, and manage technical debt
Recognize, assess, reduce, and manage technical debtRecognize, assess, reduce, and manage technical debt
Recognize, assess, reduce, and manage technical debt
 
Atlassian Bamboo Feature Overview
Atlassian Bamboo Feature OverviewAtlassian Bamboo Feature Overview
Atlassian Bamboo Feature Overview
 
Java Performance Tweaks
Java Performance TweaksJava Performance Tweaks
Java Performance Tweaks
 
Refactor to the Limit!
Refactor to the Limit!Refactor to the Limit!
Refactor to the Limit!
 
Lambdas and Laughs
Lambdas and LaughsLambdas and Laughs
Lambdas and Laughs
 

Recently uploaded

J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
Bert Jan Schrijver
 
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdfTop Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
VALiNTRY360
 
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesE-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
Quickdice ERP
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
Green Software Development
 
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Julian Hyde
 
SQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure MalaysiaSQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure Malaysia
GohKiangHock
 
Lecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptxLecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptx
TaghreedAltamimi
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
Patrick Weigel
 
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
XfilesPro
 
socradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdfsocradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdf
SOCRadar
 
Top 9 Trends in Cybersecurity for 2024.pptx
Top 9 Trends in Cybersecurity for 2024.pptxTop 9 Trends in Cybersecurity for 2024.pptx
Top 9 Trends in Cybersecurity for 2024.pptx
devvsandy
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
Philip Schwarz
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
Green Software Development
 
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
mz5nrf0n
 
E-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet DynamicsE-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet Dynamics
Hornet Dynamics
 
Modelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - AmsterdamModelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - Amsterdam
Alberto Brandolini
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
Ayan Halder
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
TheSMSPoint
 
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemUI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
Peter Muessig
 

Recently uploaded (20)

J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
 
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdfTop Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
 
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesE-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
 
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)
 
SQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure MalaysiaSQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure Malaysia
 
Lecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptxLecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptx
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
 
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
 
socradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdfsocradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdf
 
Top 9 Trends in Cybersecurity for 2024.pptx
Top 9 Trends in Cybersecurity for 2024.pptxTop 9 Trends in Cybersecurity for 2024.pptx
Top 9 Trends in Cybersecurity for 2024.pptx
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
 
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
 
E-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet DynamicsE-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet Dynamics
 
Modelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - AmsterdamModelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - Amsterdam
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
 
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemUI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
 

Functional Programming in Java

  • 1. 09 Sept 2015 Functional Programming in Java Jim Bethancourt @jimbethancourt
  • 2. 1 1 What is Functional Programming? 2 What are the Benefits? 3 Functions 4 Lambdas 5 Streams 6 Terminal Operators 7 Intermediate Operators 8 Collectors 9 Optional Agenda
  • 3. 2 What is Functional Programming? Functions have no state They don’t change • the world around them • their input • access global state Given the same input, they produce the same output Just like a function in math: f(x) = y What is Functional Programming
  • 4. 3 What is Functional Programming? Let’s face it – Computer application codebases have gotten HUGE! How big are the codebases you work on? Mutable state is frequently difficult to manage Have you forgotten to set a flag too? Imperative style code is often difficult to read Don’t tell me what you’re doing – just do it! Why Functional Programming?
  • 5. 4 1 What is Functional Programming? 2 What are the Benefits? 3 Functions 4 Lambdas 5 Streams 6 Terminal Operators 7 Intermediate Operators 8 Collectors 9 Optional
  • 6. 5 What are the Benefits? Functional Programs are easier to: • Scale • Read • Test Faster!
  • 7. 6 1 What is Functional Programming? 2 What are the Benefits? 3 Functions 4 Lambdas 5 Streams 6 Terminal Operators 7 Intermediate Operators 8 Collectors 9 Optional
  • 8. 7 Functions Functions are first-class citizens: • They can be assigned, passed, and returned just like variables! • They don’t mutate state, they transform values • Treating functions as values is known as First- class Functions or Higher-order Programming Functions as First-Class Citizens
  • 9. 8 Functions Functions are isolated But what if I want secondary output / side effects? Use a Consumer<T>! Functions Are Isolated
  • 10. 9 Functions public void convertTemps() { DoubleUnaryOperator convertFtoC = expandedCurriedConverter(-32, 5.0/9, 0); S.o.p(convertFtoC.applyAsDouble(98.6)); } static DoubleUnaryOperator expandedCurriedConverter(double w, double y, double z) { return (double x) -> (x + w) * y + z; } Example of Functional Programming
  • 11. 10 Functions Imperative vs Declarative Imperative How Mutate Side-effects Pass objects Hard to compose Declarative What Transform Pure Pass functions too Functional composition
  • 12. 11 1 What is Functional Programming? 2 What are the Benefits? 3 Functions 4 Lambdas 5 Streams 6 Terminal Operators 7 Intermediate Operators 8 Collectors 9 Optional
  • 13. 12 Lambdas A lambda is an inline functional definition They can see and use nearby values, but can’t change them Closures can change nearby variables. Java 8 lambdas are NOT closures since they require all variables to be final What are Lambdas
  • 14. 13 Lambdas Before: Comparator<Apple> byWeight = new Comparator<Apple>() { public int compare(Apple a1, Apple a2){ return a1.getWeight().compareTo(a2.getWeight()); } }; After (with lambda expressions): Comparator<Apple> byWeight = (Apple a1, Apple a2) -> a1.getWeight().compareTo(a2.getWeight()); Before and After Lambdas
  • 15. 14 1 What is Functional Programming? 2 What are the Benefits? 3 Functions 4 Lambdas 5 Streams 6 Terminal Operators 7 Intermediate Operators 8 Collectors 9 Optional
  • 16. 15 Streams A sequence of elements supporting sequential and parallel aggregate operations. (from Java 8 Javadoc) Streams allow for you to manipulate collections of data in a declarative way. Operations can be chained together to form an expressive processing pipeline Streams perform internal iteration behind the scenes, allowing you to focus on what rather than how Streams can easily be parallelized by calling parallelStream() -- YMMV What is a Stream?
  • 17. 16 Streams Each intermediate operation performed on a stream returns another stream This allows for any number of intermediate operations to be performed on a stream of elements These operations include but are not limited to filter() map() flatMap() distinct() Streams don’t perform an evaluation until they reach their terminal operation is reached, such as reduce() collect() sum(), max(), min(), etc. Streams Return Streams, and they’re Lazy!!!
  • 18. 17 1 What is Functional Programming? 2 What are the Benefits? 3 Functions 4 Lambdas 5 Streams 6 Terminal Operators 7 Intermediate Operators 8 Collectors 9 Optional
  • 19. 18 Terminal Operators Terminal operators trigger processing and return a value. reduce(), count(), anyMatch(), and summaryStatistics() are examples of terminal operations Once a terminal operation takes place, that instance of the stream is dead and no longer usable, and no further processing can take place on it. The End is Coming!
  • 20. 19 Terminal Operators Streams can only be traversed once, so how can we reuse the code we wrote? Assign the nonterminated stream operation to a stream supplier object! Supplier<Stream<String>> streamSupplier = () -> Stream.of("d2", "a2", "b1", "b3", "c") .filter(s -> s.startsWith("a")); streamSupplier.get().anyMatch(s -> true); // ok streamSupplier.get().noneMatch(s -> true); // ok One Time Traversal and Stream Reuse
  • 21. 20 1 What is Functional Programming? 2 What are the Benefits? 3 Functions 4 Lambdas 5 Streams 6 Terminal Operators 7 Intermediate Operators 8 Collectors 9 Optional
  • 22. 21 Intermediate Operators Intermediate Operators perform mapping / transforming and filtering operations on a stream of elements. Any number of intermediate operations can be performed on a stream of elements. people.stream() .filter(person -> person.getGender() == Gender.MALE) .map(person -> new Person(person.getName().toUpperCase(), person.getGender(), person.getAge())) .forEach(System.out::println); Transforming! More Than Meets the Eye!
  • 23. 22 1 What is Functional Programming? 2 What are the Benefits? 3 Functions 4 Lambdas 5 Streams 6 Terminal Operators 7 Intermediate Operators 8 Collectors 9 Optional
  • 24. 23 Collectors Collectors allow for objects to be accumulated to be passed back to a result container such as a Collection or a Map Transformations may take place once all elements are accumulated, but this is not required. Collector<Employee, ?, Map<Department, Integer>> summingSalariesByDept = Collectors.groupingBy(Employee::getDepartment, summingSalaries); Finishing the Stream
  • 25. 24 Collectors Collectors require 3 things: Empty instance of the output type Operator that can put an element into that output type Operation that can combine two of the output type Collectors within collectors are possible too! Requirements of Collectors
  • 26. 25 1 What is Functional Programming? 2 What are the Benefits? 3 Functions 4 Lambdas 5 Streams 6 Terminal Operators 7 Intermediate Operators 8 Collectors 9 Optional
  • 29. 28 Optional Instead of returning a null object, return an Optional! Use Optional as a Safe Return Type
  • 30. 29 Optional public class Person { private Optional<Car> car; public Optional<Car> getCar() { return car; } } public class Car { private Optional<Insurance> insurance; public Optional<Insurance> getInsurance() { return insurance; } } public class Insurance { private String name; public String getName() { return name; } } Putting Optional to Work
  • 31. 30 Optional Empty optional creation Optional<Car> optCar = Optional.empty(); Optional from a non-null value Optional<Car> optCar = Optional.of(car); Optional from a possibly null value Optional<Car> optCar = Optional.ofNullable(car); Creating Optionals
  • 32. 31 Optional Optional<Insurance> optInsurance = Optional.ofNullable(insurance); Optional<String> name = optInsurance.map(Insurance::getName); Getting values in Optionals
  • 33. 32 Optional This won’t compile! Optional<Person> optPerson = Optional.of(person); Optional<String> name = optPerson.map(Person::getCar) .map(Car::getInsurance) .map(Insurance::getName); Chaining Operations with Optionals
  • 34. 33 Optional Instead, use flatMap() public String getCarInsuranceName(Optional<Person> person) { return person.flatMap(Person::getCar) .flatMap(Car::getInsurance) .map(Insurance::getName) .orElse("Unknown"); } Chaining Operations with Optionals

Editor's Notes

  1. Functions are isolated – they don’t know anything about and can‘t change the outside world To allow secondary output to be passed out of a function, pass in a Consumer that will accept() this output, handing over control
  2. Thank you to Venkat Subramaniam for this helpful comparison!
  3. filter() map() flatMap() -- Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element. It lets you replace each value of a stream with another stream and then concatenates all the generated streams into a single stream.
  4. This will print out the name, gender, and age for each person object
  5. If we wanted to create a collector to tabulate the sum of salaries by department, we could reuse the "sum of salaries" logic usingCollectors.groupingBy(Function, Collector):
  6. Collectors within collectors are possible too!  groupingBy() allows for a second downstream collector to be passed that will further reduce the elements of the stream and populate them as values in the resulting map instead of populating a list of values
  7. A person might or might not have a car A car might or might not be insured
  8. There are several ways of creating optionals Third example: If car were null, the resulting Optional object would be empty.
  9. The map operation applies the provided function to each element of a stream. You could also think of an Optional object as a particular collection of data, containing at most a single element. If the Optional contains a value, then the function passed as argument to map transforms that value. If the Optional is empty, then nothing happens.
  10. With streams, the flatMap method takes a function as an argument, which returns another stream. This function is applied to each element of a stream, which would result in a stream of streams. But flatMap has the effect of replacing each generated stream by the contents of that stream. In other words, all the separate streams that are generated by the function get amalgamated or flattened into a single stream. What we want here is something similar, but you want to flatten a two-level optional into one.