SlideShare a Scribd company logo
Functional Java 8
This Ain’t Your Daddy’s JDK

Nick Maiorano
1
ThoughtFlow Solutions Inc.
About me
Developer

Software
Architect

Independent
Consultant
ThoughtFlow Solutions

Functional Java 8 – This Ain’t Your Daddy’s JDK

2
Available April 2014

Functional Java 8 – This Ain’t Your Daddy’s JDK

3
Functional Java 8 – This Ain’t Your Daddy’s JDK

4
What’s in Java 8?
Encoding
enhancements

Encryption
updates

Functional
libraries

Concurrency
Modularization

Repeating
annotations

New
Date/Time
API

Concurrency
updates

Java 8
Lambdas
Nashorn
JavaScript
Engine

Church
Performance
improvements

Functional Java 8 – This Ain’t Your Daddy’s JDK

GC
updates

Collections

5
What’s in Java 8?
Functional
libraries

Concurrency

Java 8
Lambdas

Church

Functional Java 8 – This Ain’t Your Daddy’s JDK

Collections

6
The rocky road to lambdas
•
•
•
•
•
•

Lambdas too difficult in late 1990s
BGGA project initiated in 2007
JSR 335 filed in late 2009
Had to fit type system
Maintain backward compatibility
Java community divided

Functional Java 8 – This Ain’t Your Daddy’s JDK

7
The rocky road to lambdas
•
•
•
•

To be released as part of Java 7
To be released in September 2013
To be released in March 2014
Completing 7 years of work

Functional Java 8 – This Ain’t Your Daddy’s JDK

8
Functional Programming
• Rooted in lambda calculus
• Hastened by death of Moore’s law
• Programming paradigm of the times

Functional Java 8 – This Ain’t Your Daddy’s JDK

9
Java DNA
Structured

Reflective

Object
Oriented

Imperative

Concurrent
Generic

Generic
Java DNA
Structured

Reflective

Object
Oriented

Functional

Imperative

Concurrent
Generic

Generic
Organization
Java

Classes
Vs.

FP

Functional Java 8 – This Ain’t Your Daddy’s JDK

Functions

12
Building blocks
Java

Polymorphism, encapsulation,
inheritance, dynamic binding
Vs.

FP

Functional Java 8 – This Ain’t Your Daddy’s JDK

Higher-order functions, currying,
monads, list comprehensions

13
Algorithmic style
Java

Imperative: define behaviour as a
series of steps
Vs.

FP

Functional Java 8 – This Ain’t Your Daddy’s JDK

Declarative: binding functions together
without necessarily specifying their
contents

14
State management
Java

Put state and behaviour together
Vs.

FP

Functional Java 8 – This Ain’t Your Daddy’s JDK

Avoid state

15
Mutability
Java

Supports mutability & immutability
Vs.

FP

Functional Java 8 – This Ain’t Your Daddy’s JDK

Emphasis on immutability

16
Design patterns
Java

Relies on design patterns to
complement OOP for a higher level of
abstraction
Vs.

FP

Functional Java 8 – This Ain’t Your Daddy’s JDK

Is already a higher level abstraction

17
Concurrency
Java

Use multi-threading, control access to
shared resources via locks
Vs.

FP

Functional Java 8 – This Ain’t Your Daddy’s JDK

Organize processing into parallel workflows
each dedicated to a core and avoid state,
shared resources and locks

18
Recursion
Java

Supported with limitations
Vs.

FP

Functional Java 8 – This Ain’t Your Daddy’s JDK

Rudimentary

19
Expressiveness
Java

Clear & verbose
Vs.

FP

Functional Java 8 – This Ain’t Your Daddy’s JDK

Concise & dense

20
Functional Java
“…Is a blend of imperative and object
oriented programming enhanced
with functional flavors”

Functional Java 8 – This Ain’t Your Daddy’s JDK

21
Functional Java 8 – This Ain’t Your Daddy’s JDK

22
New Syntax
•
•
•
•

Lambdas
Functional interfaces
Method references
Default methods

Functional Java 8 – This Ain’t Your Daddy’s JDK

23
What’s a lambda?

Functional Java 8 – This Ain’t Your Daddy’s JDK

24
Anatomy of the lambda
• Behavior-as-data facilitators
• On-the-fly code definers
• Ground-floor of FP

Functional Java 8 – This Ain’t Your Daddy’s JDK

25
Anatomy of the lambda
Lambda blocks
(Parameter declaration) -> {Lambda body}

(Integer i) -> {System.out.println(i);};

Functional Java 8 – This Ain’t Your Daddy’s JDK

26
Anatomy of the lambda
Lambda blocks
(Parameter declaration) -> {Lambda body}

(Integer i) -> {System.out.println(i);};

Functional Java 8 – This Ain’t Your Daddy’s JDK

27
Anatomy of the lambda
Lambda expressions
Parameter name -> Lambda expression

(Integer i) -> {System.out.println(i);};

Functional Java 8 – This Ain’t Your Daddy’s JDK

28
Anatomy of the lambda
Lambda expressions
Parameter name -> Lambda expression

i -> System.out.println(i);

Functional Java 8 – This Ain’t Your Daddy’s JDK

29
Anatomy of the lambda
Lambda expressions
Parameter name -> single statement;

i -> i * 2;

Functional Java 8 – This Ain’t Your Daddy’s JDK

No return statement

30
Functional Interfaces
• Lambdas are backed by interfaces
• Single abstract methods
• @FunctionalInterface

Functional Java 8 – This Ain’t Your Daddy’s JDK

31
Functional Interfaces
@FunctionalInterface
public interface Calculator
{
int calculate(int x, int y);
}

Functional Java 8 – This Ain’t Your Daddy’s JDK

32
Functional Interfaces
Calculator multiply = (x, y) -> x * y;
Calculator divide = (x, y) -> x / y;

int product = multiply.calculate(10, 20);
int quotient = divide.calculate(10, 20);
someMethod(multiply, divide);
anotherMethod((x, y) -> x ^ y);
Functional Java 8 – This Ain’t Your Daddy’s JDK

33
Functional Interfaces
• Over 40 functional interfaces in JDK 8
• Rarely need to define your own
• Generic and specialized

Functional Java 8 – This Ain’t Your Daddy’s JDK

34
Functional Interfaces
Consumer

Supplier<T>
T get()

Supplier

Functional
Interfaces

Consumer<T>
void accept(T t);

Function

Function <T, R>
R apply(T t);

Predicate

Predicate<T>
boolean test(T t);

Functional Java 8 – This Ain’t Your Daddy’s JDK

35
Method References
Calculator maxFinder = (x, y) -> Math.max(x, y);

Functional Java 8 – This Ain’t Your Daddy’s JDK

36
Method References
Calculator maxFinder = Math::max;
Math
Calculator

int max(int a, int b);
int calculate(int x, int y);

Functional Java 8 – This Ain’t Your Daddy’s JDK

37
Method References
Type

Template

Static

Class::method

Instance

instanceVariable::method

Constructor

Class::new

Super

super::method

Generic constructor

Class<Type>::new

Array

Class[]::new

Functional Java 8 – This Ain’t Your Daddy’s JDK

38
Anonymous classes?
• Do we still need anonymous classes?
• Lambdas are behavior-only – no state
• Only single abstract methods

Functional Java 8 – This Ain’t Your Daddy’s JDK

39
Default Methods
@FunctionalInterface
public interface Calculator
{
int calculate(int x, int y);
default int multiply(int x, int y)
{
return x * y;
}
}
Functional Java 8 – This Ain’t Your Daddy’s JDK

40
Default Methods
• Can be overloaded
• Can be static or instance based
• Introduce multiple inheritance

Functional Java 8 – This Ain’t Your Daddy’s JDK

41
Functional Java 8 – This Ain’t Your Daddy’s JDK

42
Java-style functional programming
• Other languages support FP natively
• Java supports FP through libraries

Functional
interfaces

Functional

Java
Streams

Collections

Functional Java 8 – This Ain’t Your Daddy’s JDK

43
Functionalized Collections

Functional Java 8 – This Ain’t Your Daddy’s JDK

44
Functionalized Lists
List<String> stooges =
Arrays.asList("Larry", "Moe", "Curly");

stooges.forEach(s -> System.out.println(s);

Functional Java 8 – This Ain’t Your Daddy’s JDK

45
Functionalized Lists
List<String> stooges =
Arrays.asList("Larry", "Moe", "Curly");

stooges.forEach(System.out::println);

Functional Java 8 – This Ain’t Your Daddy’s JDK

46
Functionalized Lists
Function<String, String> feminize =
s -> "Larry".equals(s) ? "Lara" :
"Moe".equals(s) ? "Maude" : "Shirley";
stooges.replaceAll(feminize);

Functional Java 8 – This Ain’t Your Daddy’s JDK

47
Functionalized Lists
Predicate<String> moeRemover =
s -> “Moe".equals(s);

stooges.removeIf(moeRemover);

Functional Java 8 – This Ain’t Your Daddy’s JDK

48
Functionalized Maps
Map<Integer, List<String>> movieDb = new HashMap<>();
movieDb.computeIfAbsent(1930, k -> new LinkedList<>());
movieDb.compute(1930, (k, v) -> { v.add(“Soup to nuts”);
return v;});

Functional Java 8 – This Ain’t Your Daddy’s JDK

49
Functionalized Maps
movieDb.putIfAbsent
(1930, new LinkedList<>());

movieDb.getOrDefault
(1930, new LinkedList<>());

Functional Java 8 – This Ain’t Your Daddy’s JDK

50
Streams

Functional Java 8 – This Ain’t Your Daddy’s JDK

51
Streams
Lambda

Stream

Operation 1

Functional Java 8 – This Ain’t Your Daddy’s JDK

Lambda

Operation 2

Lambda

Operation 3

Lambda

Operation 4

52
Streams
Build

Peek

Filter

Stream
operations
Iterate

Map

Reduce

Functional Java 8 – This Ain’t Your Daddy’s JDK

53
Streams
private static boolean isPerfect(long n)
{
long sum = 0;
for (long i = 1; i <= n / 2; i++)
{
if (n % i == 0)
{
sum += i;
}
}

return sum == n;
}
Functional Java 8 – This Ain’t Your Daddy’s JDK

54
Streams
private static boolean isPerfect(long n)
{
return n > 0 &&
LongStream.rangeClosed(1, n / 2).
filter(i -> n % i == 0).
reduce(0, (l, r) -> l + r) == n;
}

Functional Java 8 – This Ain’t Your Daddy’s JDK

55
Streams
•
•
•
•

Declarative constructs
Can abstract any imperative for/while loop
Work best when adhering to FP principles
Easily parallelizable

Functional Java 8 – This Ain’t Your Daddy’s JDK

56
Parallel Streams
private static boolean isPerfect(long n)
{
return n > 0 &&
LongStream.rangeClosed(1, n / 2).
filter(i -> n % i == 0).
reduce(0, (l, r) -> l + r) == n;
}

Functional Java 8 – This Ain’t Your Daddy’s JDK

57
Parallel Streams
private static boolean isPerfect(long n)
{
return n > 0 &&
LongStream.rangeClosed(1, n / 2). parallel().
filter(i -> n % i == 0).
reduce(0, (l, r) -> l + r) == n;
}

Functional Java 8 – This Ain’t Your Daddy’s JDK

58
Parallel Streams

Functional Java 8 – This Ain’t Your Daddy’s JDK

59
Parallel Streams

Functional Java 8 – This Ain’t Your Daddy’s JDK

60
Parallel Streams
• Uses fork-join used under the hood
• Thread pool sized to # cores
• Order can be changed

Functional Java 8 – This Ain’t Your Daddy’s JDK

61
Parallel Streams
private static boolean isPerfect(long n)
{
return n > 0 &&
LongStream.rangeClosed(1, n / 2). parallel().
filter(i -> n % i == 0).
reduce(0, (l, r) -> l + r) == n;
}

Functional Java 8 – This Ain’t Your Daddy’s JDK

62
Parallel Streams
private static boolean isPerfect(long n)
{
return n > 0 &&
LongStream.rangeClosed(1, n / 2). parallel().
filter(i -> n % i == 0).
reduce(0, (l, r) -> l + r) == n;
}
List<Long> perfectNumbers =
LongStream.rangeClosed(1, 8192).
filter(PerfectNumberFinder::isPerfect).
collect(ArrayList<Long>::new, ArrayList<Long>::add, ArrayList<Long>::addAll);

Functional Java 8 – This Ain’t Your Daddy’s JDK

63
Parallel Streams
private static boolean isPerfect(long n)
{
return n > 0 &&
LongStream.rangeClosed(1, n / 2). parallel().
filter(i -> n % i == 0).
reduce(0, (l, r) -> l + r) == n;
}
List<Long> perfectNumbers =
LongStream.rangeClosed(1, 8192).parallel().
filter(PerfectNumberFinder::isPerfect).
collect(ArrayList<Long>::new, ArrayList<Long>::add, ArrayList<Long>::addAll);

Functional Java 8 – This Ain’t Your Daddy’s JDK

64
Parallel Streams
8,128
33,550,336
8,589,869,056
137,438,691,328

Functional Java 8 – This Ain’t Your Daddy’s JDK

Imperative
0
190
48648
778853

Serial
Stream

1
229
59646
998776

Parallel
Stream

0
66
13383
203651

65
Parallelization
• Must avoid side-effects and mutating state
• Problems must fit the associativity property
• Ex: ((a * b) * c) = (a * (b * c))

• Must be enough parallelizable code
• Performance not always better
• Can’t modify local variables (unlike for loops)

Functional Java 8 – This Ain’t Your Daddy’s JDK

66
Streams (the good)
•
•
•
•

Allow abstraction of details
Communicate intent clearly
Concise
On-demand parallelization

Functional Java 8 – This Ain’t Your Daddy’s JDK

67
Streams (the bad)
•
•
•
•

Loss of flexibility and control
Increased code density
Can be less efficient
On-demand parallelization

Functional Java 8 – This Ain’t Your Daddy’s JDK

68
Functional Java 8 – This Ain’t Your Daddy’s JDK

69
Final thoughts on
Java 8

Functional Java 8 – This Ain’t Your Daddy’s JDK

70
How good is functional Java?
•
•
•
•
•
•

Java now supports functional constructs
But still OO at its core
Functional expressions a little clunky
Generics require more mental agility
Conciseness is compromised
Recursion not industrial strength

Functional Java 8 – This Ain’t Your Daddy’s JDK

71
How good is functional Java?
• FP integrated cohesively & coherently
• New tools available for the masses

Functional Java 8 – This Ain’t Your Daddy’s JDK

72
Available at Amazon April 2014

Functional Java 8 – This Ain’t Your Daddy’s JDK

73
@ThoughtFlow_Inc

Functional Java 8 – This Ain’t Your Daddy’s JDK

74
Questions

Functional Java 8 – This Ain’t Your Daddy’s JDK

75

More Related Content

PDF
Intro to Java 8 Closures (Dainius Mezanskas)
PDF
Scala coated JVM
PDF
camel-scala.pdf
PPTX
Modern Java Workshop
PPT
55 New Features in Java 7
PPTX
Java 8 Feature Preview
PDF
Java 7 New Features
PDF
Java 5 and 6 New Features
Intro to Java 8 Closures (Dainius Mezanskas)
Scala coated JVM
camel-scala.pdf
Modern Java Workshop
55 New Features in Java 7
Java 8 Feature Preview
Java 7 New Features
Java 5 and 6 New Features

What's hot (20)

PPTX
New Features in JDK 8
ODP
Refactoring to Scala DSLs and LiftOff 2009 Recap
PDF
Java 8 features
PDF
Smart Migration to JDK 8
PDF
Kotlin advanced - language reference for android developers
PDF
Java 8 features
PPTX
The Dark Side Of Lambda Expressions in Java 8
PDF
Modern Programming in Java 8 - Lambdas, Streams and Date Time API
PPT
JDK1.6
PDF
A Brief, but Dense, Intro to Scala
PPTX
Java 8 Features
PDF
New Features Of JDK 7
PDF
Productive Programming in Java 8 - with Lambdas and Streams
PPTX
Java SE 8 - New Features
PDF
Spark workshop
PPTX
Java 8 lambda
PDF
Kotlin in action
PPTX
PDF
Scala : language of the future
PDF
Advanced Production Debugging
New Features in JDK 8
Refactoring to Scala DSLs and LiftOff 2009 Recap
Java 8 features
Smart Migration to JDK 8
Kotlin advanced - language reference for android developers
Java 8 features
The Dark Side Of Lambda Expressions in Java 8
Modern Programming in Java 8 - Lambdas, Streams and Date Time API
JDK1.6
A Brief, but Dense, Intro to Scala
Java 8 Features
New Features Of JDK 7
Productive Programming in Java 8 - with Lambdas and Streams
Java SE 8 - New Features
Spark workshop
Java 8 lambda
Kotlin in action
Scala : language of the future
Advanced Production Debugging
Ad

Viewers also liked (20)

PPTX
Functional programming with_jdk8-s_ritter
PPTX
Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...
DOC
Java Class Loading
PPTX
Java class loader
PDF
Application of Ontology in Semantic Information Retrieval by Prof Shahrul Azm...
PPT
Incremental Evolving Grammar Fragments
PDF
Classloading and Type Visibility in OSGi
PDF
Carbon and OSGi Deep Dive
PDF
OSGi Presentation
PDF
Lambdas And Streams Hands On Lab
PPTX
Self adaptive based natural language interface for disambiguation of
PDF
Open Services Gateway Initiative (OSGI)
PPTX
Java Modularity with OSGi
PDF
Apache Karaf - Building OSGi applications on Apache Karaf - T Frank & A Grzesik
PDF
The Full Stack Java Developer - Josh Long
PPTX
Introduction to-osgi
PDF
OSGi Blueprint Services
PDF
Microservices OSGi-running-with-apache-karaf
KEY
Regular Expressions 101
PDF
Lecture: Regular Expressions and Regular Languages
Functional programming with_jdk8-s_ritter
Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...
Java Class Loading
Java class loader
Application of Ontology in Semantic Information Retrieval by Prof Shahrul Azm...
Incremental Evolving Grammar Fragments
Classloading and Type Visibility in OSGi
Carbon and OSGi Deep Dive
OSGi Presentation
Lambdas And Streams Hands On Lab
Self adaptive based natural language interface for disambiguation of
Open Services Gateway Initiative (OSGI)
Java Modularity with OSGi
Apache Karaf - Building OSGi applications on Apache Karaf - T Frank & A Grzesik
The Full Stack Java Developer - Josh Long
Introduction to-osgi
OSGi Blueprint Services
Microservices OSGi-running-with-apache-karaf
Regular Expressions 101
Lecture: Regular Expressions and Regular Languages
Ad

Similar to Functional java 8 (20)

PDF
Java jdk-update-nov10-sde-v3m
PDF
Java 8 Lambda
PDF
Reaching the lambda heaven
PPTX
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
PPTX
Fundamentals of java --- version 2
PPTX
1 Module 1 Introduction.pptx
PDF
Java 8 Overview
KEY
Polyglot and functional (Devoxx Nov/2011)
PDF
Java Webinar #12: "Java Versions and Features: Since JDK 8 to 16"
PDF
Java SE 8
PDF
Developing android apps with java 8
PDF
InterConnect 2016, OpenJPA and EclipseLink Usage Scenarios (PEJ-5303)
PDF
Java Future S Ritter
PDF
ADBA (Asynchronous Database Access)
PDF
AMIS Oracle OpenWorld 2013 Review Part 3 - Fusion Middleware
PDF
What to expect from Java 9
PPTX
Java 7 & 8
KEY
Polyglot and Functional Programming (OSCON 2012)
PPTX
55 New Features in Java SE 8
PPTX
Scala-Ls1
Java jdk-update-nov10-sde-v3m
Java 8 Lambda
Reaching the lambda heaven
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
Fundamentals of java --- version 2
1 Module 1 Introduction.pptx
Java 8 Overview
Polyglot and functional (Devoxx Nov/2011)
Java Webinar #12: "Java Versions and Features: Since JDK 8 to 16"
Java SE 8
Developing android apps with java 8
InterConnect 2016, OpenJPA and EclipseLink Usage Scenarios (PEJ-5303)
Java Future S Ritter
ADBA (Asynchronous Database Access)
AMIS Oracle OpenWorld 2013 Review Part 3 - Fusion Middleware
What to expect from Java 9
Java 7 & 8
Polyglot and Functional Programming (OSCON 2012)
55 New Features in Java SE 8
Scala-Ls1

Recently uploaded (20)

PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Chapter 3 Spatial Domain Image Processing.pdf
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
KodekX | Application Modernization Development
PDF
Approach and Philosophy of On baking technology
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Empathic Computing: Creating Shared Understanding
PPTX
Spectroscopy.pptx food analysis technology
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Building Integrated photovoltaic BIPV_UPV.pdf
Review of recent advances in non-invasive hemoglobin estimation
20250228 LYD VKU AI Blended-Learning.pptx
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Chapter 3 Spatial Domain Image Processing.pdf
The AUB Centre for AI in Media Proposal.docx
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Digital-Transformation-Roadmap-for-Companies.pptx
KodekX | Application Modernization Development
Approach and Philosophy of On baking technology
Understanding_Digital_Forensics_Presentation.pptx
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Encapsulation_ Review paper, used for researhc scholars
Diabetes mellitus diagnosis method based random forest with bat algorithm
Programs and apps: productivity, graphics, security and other tools
Empathic Computing: Creating Shared Understanding
Spectroscopy.pptx food analysis technology

Functional java 8