SlideShare a Scribd company logo
TALHA OCAKÇI WWW.JAVATHLON.COM
FUNCTIONAL PROGRAMMING
IN JAVA 8
www.javathlon.com
GREATEST  UPDATE  TO  JAVA
✤ Inspired by JVM languages such as Scala and
Clojure and frameworks like Guava.
✤ Rise of functional programming
www.javathlon.com
WHAT  IS  FUNCTIONAL  PROGRAMMING?
✤ A programming style that treats computation as the evaluation of mathematical
functions and avoids changing-state and mutable data.
✤ f(x) = y g(f(x)) = z
✤ Based on lambda calculus. (Some inputs are transformed to some output without
modifying the input)
✤ No iteration, no for loop, no variable.
www.javathlon.com
NO  ITERATION?
✤ What? Without a for loop, how I will process all
elements of an ArrayList?
✤ Yes seems weird. You need to change your
mindset. Mind bending at first.
www.javathlon.com
FUNCTION…  YOU  MEAN  METHOD???
✤ No, I don’t mean the methods inside a class.
✤ FUNCTION IS NOT METHOD!
✤ Methods are not independent program units and they are bound to another context, like an
object instance or class.
✤ Methods may depend upon values other than its arguments
✤ Methods may change the values of its arguments or some other static values.
✤ Pure functions are opposite.
www.javathlon.com
WHAT  IS  A  FUNCTION?
✤ Lives independently
✤ Does not depend to any value other than its arguments
✤ Output of a function is a value or another function
✤ Does not change any argument’s value or any other external value. (no side
effects)
✤ Functions may be composed together regardless of the context
www.javathlon.com
WHAT  IS  FUNCTIONAL  PROGRAMMING
✤ Functions exist independently. Not bound to objects or classes
✤ Functions can not change the state of any object or value
✤ All values are immutable. Hates mutability!
✤ No iteration. Operations are done by recursion.
www.javathlon.com
Why  so  afraid  of  mutability?
Did  you  ever  wonder  why  most  
solutions  to  program  glitches  are  fixed  
by  rebooting  your  computer  or  
restarting  the  offending  application?    
That’s  because  of  state.  The  program  
has  corrupted  its  state.
www.javathlon.com
Why  so  afraid  of  mutability?
✤ Do you remember synchronised keyword, Barriers,
Semaphores, Locks and their lack of sweetness?
✤ Have you ever scratched your hair because of deadlocks,
thread starving, unexpected values of non-atomic object
operations?
✤ We created the devil, intentionally, ourselves. We! Phew!
Why?
www.javathlon.com
How  to  prevent  multithread  problems?
✤ Prevent mutability
✤ If mutability is important, put the synchronisation block in the object.
✤ Use AtomicInteger instead of Integer
✤ Use ConcurrentHashMap instead of HashMap…
www.javathlon.com
MULTICORE  SUPPORT  AND  THREAD  
SYNCHRONIZATION  IN  JAVA
✤ Fork/Join for multicore in Java
✤ Thread and ThreadPool for multi-thread
✤ Leverage all cores of CPU. Distribute the tasks each core and then combine the
results.
www.javathlon.com
BIG-­‐DATA  AND  MAP-­‐REDUCE
✤ Huge data is processed in chunks,
each chunk yields an intermediate
form of data.
✤ Intermediate data is combined into
single result.
✤ None of the functions may affect each
other but simply yield a single result
without a side effect.
www.javathlon.com
BIGDATA  AND  MAP-­‐REDUCE
Mapper Combinator
www.javathlon.com
BIGDATA  AND  MAP-­‐REDUCE
✤ Each operation must be an
independent pure function.
✤ So, functional programming is cut out
for these type of problems.
www.javathlon.com TALHA OCAKÇI
FUNCTIONAL OBJECT ORIENTED JAVA 8
Where is functions? Independent
Bound to object or
classes. Called as
method.
Functional interface
(Seems independent but bound to
object or class again)
Value state Immutable Mutable Immutable if you desire
Function chaining Yes Yes if in same instance Lambda functions may chain
Synchronization and
multicore support
Great!!!
Exist but really a
cumbersome
So much easy than Java 7.
www.javathlon.com
IMPERATIVE  VS  FUNCTIONAL
www.javathlon.com
ELEMENTS  OF  FUNCTIONAL  
PROGRAMMING
✤Immutable state (yes, get rid of mutable state, the evil.)
✤No side effects of function apply. (Input arguments are not modified)
✤No iteration. Only recursion
✤Function references and function compositions
✤Higher order functions(functions may be passed as arguments to other functions) and currying (partial evaluation)
✤Lazy evaluation of collections
✤No null value
✤Closure
✤Monad
www.javathlon.com
JAVA  8  PRETENDS  TO  BE  A  FUNCTIONAL  
PROGRAMMING  LANGUAGE
Attribute Java 8 Solution (or pretend to be a solution)
Immutable state
final keyword, Immutable collections
(Collections.unmodifiableX). Both make the objects and the
collection itself immutable.
Declarative. Not imperative Use Streams
No iteration. Only recursion
No for loop on collections. Instead use Streams and its
methods.
Function references and
function composition
All FunctionalInterfaces such as Function, Predicate,
Consumer, Supplier interfaces and lambda expressions.
www.javathlon.com
JAVA  8  FUNCTIONAL  PROGRAMMING  
ELEMENTS
Attribute Java 8 Solution (or pretend to be a solution)
Higher order functions and currying Manuel implementation, no real built-in
solution
Lazy evaluation of collections take() method of Stream
No null value Optional class
Monad Stream and Optional …
Function Chaining Built-in with Function interface
Closure Only with final variables
www.javathlon.com
SUMMARY
✤ Java 8 brings functional programming elements into the language not in an
academical and formal level but has a goodwill to have them
✤ Lambda expressions
✤ Stream
✤ @FunctionalInterface and some others…
www.javathlon.com
FINAL  -­‐  IMMUTABLE  OBJECTS
✤ final keyword makes what final?
✤ final Date d = new Date();
✤ d = new Date() // legal?
✤ d.setTime(23234234); // legal?
www.javathlon.com
FINAL  IMMUTABLE  OBJECTS
✤ final only protects the address changes. Can not protect state modifications.
✤ You must explicitly protect attributes with private access modifier and then prevent
setter methods.
✤ LocalDate is announced as immutable Date object in Java 8.
www.javathlon.com
FUNCTIONAL  INTERFACE
✤ Formal definition: Single Abstract Method interfaces
✤ An interface with only one abstract method.
✤ Function, BiFunction, Predicate, Supplier and Consumer interfaces are function
interfaces that come or gain importance with Java 8.
✤ Known are Runnable interface with run() method; Comparable with compare()
method.
www.javathlon.com
FUNCTIONAL  INTERFACES
Interface Input Output Goal
Function Single object of any type Single object of any type
1. Applying a logic
2. Logic chaining
BiFunction Two objects of any type Single object of any type
1. Applying a logic
2. Logic chaining
Predicate Single object of any type boolean
Tests if a value conforms to
a logic
Consumer Single object of any type None
Using a value and output
some side effect
Supplier None Single object of any type
Create an object of desired
type
www.javathlon.com
FUNCTION  INTERFACE
✤ Used for creating a an output object based on a given input and the logic and
possibly chaining with other functions.
✤ A logic can be packaged as a variable.
www.javathlon.com
FUNCTION  INTERFACE
✤ Used for creating a an output object based on a given input and the logic and possibly chaining with
other functions.
public interface Function<T,R>
Layers  
Tools  that  allow  
Layers  
Tools  that  allow  Apply  logic  
Chain   Compose  
Unit  
R apply(T t)
Applies logic to T and returns an
object of R
andThen(Function after)
First applies its logic then the
logic provided by Function after
compose(Function before)
First applies before logic then its
own logic
identity() Returns its own input argument
www.javathlon.com
APPLYING  A  FUNCTION
www.javathlon.com
CHAINING  FUNCTION
Find	
  word	
  
count
Number	
  to	
  
string
talha ocakci java 3 1 One
We have 2 functions written before
www.javathlon.com
CHAINING  FUNCTION
Find	
  word	
  
count
Number	
  to	
  
string
talha ocakci java One
Compose them as returning the word count in a string as text
www.javathlon.com
CHAINING  FUNCTION
Find	
  word	
  
count
Number	
  to	
  
string
talha ocakci java 3 1 One
www.javathlon.com
CHAINING  FUNCTION
Simple Function invocation:
findWordCount.apply(“talha ocakci java”) => 3
numberToString.apply(2) => “two”
Function Chaining
findWordCount.andThen(numberToString).apply(“talha ocakci java”) => “three”
Find	
  word	
  
count
Number	
  to	
  
string
talha ocakci java 3 3 “three”
andThen
www.javathlon.com
FUNCTION  CHAINING  RULE
✤ Output type of first function must be a super class or the same class of the input of
second function’s input
Find	
  word	
  
count
Number	
  to	
  
string
talha ocakci java 3 3 “three”
andThen
www.javathlon.com
FUNCTION  CHAINING  RULE
✤ Otherwise ClassCastException is thrown.
Uppercase	
  
sentence
Number	
  to	
  
string
talha ocakci TALHA OCAKCI ????
andThen
TALHA OCAKCI
www.javathlon.com
PREDICATE
✤ Tests if a data conforms to some value or logic
? = is yellow
true = valid
false = not valid
www.javathlon.com
PREDICATE  INTERFACE
✤Tests if a data conforms to some value or logic
✤Logical operations can be used
public interface Function<T,R>
Layers  
Tools  that  allow  
Layers  
Tools  that  allow  Test  data  
or   Negate  
and  
boolean test(T t) Tests if t conforms to a logic
and(Predicate otherPredicate)
Logical and operation with
another predicate
or(Predicate otherPredicate)
Logical or operation with
another predicate
negate() Logical not operation
www.javathlon.com
USING  PREDICATE
✤ First predicate tests if given
string has word “Download”
✤ Second predicate tests if text’s
length is less than 50.
www.javathlon.com
USING  PREDICATE
✤ specialWordChecker.test(“Download now”);
✤ returns true
✤ sizeChecker.test(“Download now”);
✤ returns true
www.javathlon.com
LOGICAL  OPERATIONS  ON  PREDICATE
✤ Check if the string has less than 50 characters and
contains word download by using existing Predicates
✤ sizeChecker.and(specialWordChecker).test(“Download now”)
www.javathlon.com
SUPPLIER
✤ Supplies an instance of given type by constructor or some other ways.
.
www.javathlon.com
SUPPLIER  INTERFACE
T get() Supplies you a T instance
✤ Supplies an instance of given type buy constructor or some other ways.
www.javathlon.com
USING  SUPPLIER
www.javathlon.com
CONSUMER
✤ Gets an object, uses it but does not return a response.
✤ It possibly side-effects such as changing the value of the object or writing some
output to somewhere.
.
write something to somewhere
www.javathlon.com
CONSUMER  INTERFACE
void accept(T t)
Uses instance t, modifies it if necessary
Does something without returning an
output
void andThen(Consumer otherconsumer) chains consumers
✤ Gets an object, uses it but does not return a response.
✤ It possibly side-effects such as changing the value of the object or writing some
output to somewhere.
www.javathlon.com
USING  CONSUMER
www.javathlon.com
LAMBDA  EXPRESSIONS
✤ Simplifying the usage of Function, Predicate, Consumer, Supplier interfaces lambda
expressions are used.
✤ All methods of these interfaces may be changed with these : ->
✤ This expression may be referred with the proper interface reference.
✤ JVM understands which method to use.
www.javathlon.com
CONVERTING  A  DEFINITION  TO  LAMBDA  
EXPRESSION
t -> t.contains(“Download”)
www.javathlon.com
VALID  LAMBDA  EXPRESSIONS
(parameters) -> expression (List<String> list) -> list.isEmpty()
(parameters) -> {return … ;} (int a, String b) -> {
System.out.println(a);
return b +a ; }
}(parameters) -> statements (int a, int b) -> a * b
(parameters) -> statements (int a, int b) -> {return a * b;}
www.javathlon.com
LAMBDA  EXPRESSIONS
✤ -> automatically detects the proper interface, according to the return value and then
invokes the proper method.
✤ t -> t.contains(“Download”)
✤ Since right hand side returns a boolean, JVM understands that it should use a
Predicate. So implicitly creates a Predicate and then invoke test() method.
www.javathlon.com
LAMBDA  EXPRESSIONS
✤ -> automatically detects the proper interface, according to the return value and then
invokes the proper method.
✤ t -> System.out.println(“t + “is my string””)
✤ Since right hand side returns nothing, JVM implicitly creates a Consumer and
invokes apply method automatically.
www.javathlon.com
LAMBDA  EXPRESSIONS
✤ -> automatically detects the proper interface, according to the return value and then
invokes the proper method.
✤ t -> t * 3;
✤ Since right hand side accepts an input and returns a value, JVM implicitly creates a
Function instance and invoke apply method automatically.
www.javathlon.com
REFERRING  TO  A  LAMBDA  EXPRESSION
www.javathlon.com
REFERENCING  TO  LAMBDA  EXPRESSION
✤ This fails because right hand side of lambda returns nothing. Then it is not a
Function but Consumer. Thus, below reference is correct.
www.javathlon.com
REFERENCING  TO  A  FUNCTION
1
2
3
www.javathlon.com
FUNCTION  CURRYING
✤ Currying is evaluating function arguments one by one, producing a new function
with one argument less on each step.
www.javathlon.com
METHOD  AND  CONSTRUCTOR  
REFERENCES      (  ::  operators  )
✤ You don’t have to write a function from scratch every time. You may refer to a
method or constructor of a class or instance.
✤ :: operator is used for accessing static method of a class or an instance method
www.javathlon.com
AVOIDING  NULL
✤ Null is a value that is not actually a value.
✤ Hard to determine whether the value not
present or just has no value
✤ Null is mentioned as “millon dollar mistake”
✤ Functional programming avoids null
✤ Instead, each language has a structure for
determining if a reference holds a real value or not.
✤ It is Optional in Java.
www.javathlon.com
OPTIONAL
✤ In functional programming, we chain functions. If
somewhere in the chain, null is obtained,
NullPointerException may be thrown.
✤ Between the chain items, we should be able to check if a
value present.
✤ This is done by ifPresent() method of an Optional
instance.
A value exists inside?
Yes, take it
No, do you
want me to
supply
something else?
www.javathlon.com
OPTIONAL
✤ Optional<String> myOptional = Optional.of(“test”);
✤ This says, a string may exist inside. get it with get() method
✤ If a value presents get it, or supply it with something else getOrElse(Supplier s)
✤ Check if a value presents with isPresent()
✤ Do something if value presents ifPresent(Consumer consumer)
www.javathlon.com TALHA OCAKÇI
STREAM
www.javathlon.com TALHA OCAKÇI
Collection
Stream maker
Collection+
+
+
Copy the reference
and pass stream funnel
one by one
+
✤ Stream is the structure for processing a
collection in functional style.
✤ Original collection is not modified.
✤ Stream may be processed only once. After
getting an output you can not use it again.
STREAM
www.javathlon.com TALHA OCAKÇI
Stream maker
Filter
reds
Make them
triangle
with same
area
Filter small
triangles
Sum up
circumferences
20
You may stop processing in any
of these steps
www.javathlon.com
STREAM  IN  JAVA  8
Each of these boxes is an functional interface:
Function, Mapper, Supplier, Consumer, Predicate
Stream may be created with stream()
method of Collection.
20
www.javathlon.com
INTERMEDIATE  AND  TERMINAL  
OPERATIONS
✤ Intermediate operations yield a new
Stream and you may pipeline(chain) the
operations
✤ Terminal operations yield a result other
than a stream: A list, Integer etc…
✤ After a terminal operation, you can
not use the stream again and you can
not pipeline another function.
Intermediate
operations
Terminal
operations
www.javathlon.com
INTERMEDIATE  OPERATIONS
Stream Operation Goal Input
filter Filter items according to a given predicate Predicate
map Processes items and transforms Function
limit Limit the results int
sorted Sort items inside stream Comparator
distinct
Remove duplicate items according to
equals method of the given type
www.javathlon.com
TERMINAL  OPERATIONS
STREAM OPERATION GOAL INPUT
forEach
For every item, outputs
something
Consumer
count Counts current items
collect
Reduces the stream into a
desired collection
www.javathlon.com
INITIALIZE  A  STREAM
✤ You may initialise a stream by using
✤ An existing Collection’s stream() method
✤ From scratch
www.javathlon.com
CONVERTING  COLLECTIONS  TO  STREAM
✤ You may use stream() method of any collection.
✤ Original collection is not effected during the process
✤ You can’t process a stream after you get an output.
Collection
Stream maker
+
www.javathlon.com
CONVERTING  COLLECTIONS  TO  STREAM
www.javathlon.com
CREATE  STREAM  FROM  SCRATCH
✤ You may use of() method of
stream. Put the values as
comma separated.
✤ Use IntStream,
DoubleStream, LongStream
and range() method of
them.
www.javathlon.com
FILTER
✤ Includes the items that conform to given Predicate and creates a new stream.
? = is yellow
true = valid
false = not valid
www.javathlon.com
MAP
✤ All items are converted to a new state or a new type.
✤ Logic is assigned with a Function.
REDUCTION
Combining  items  according  to  a  logic
www.javathlon.com
WHAT  IS  REDUCTION?
✤ A reduction operation (also called as fold) takes a sequence of input elements and
combines them into a single summary result by repeated application of a
combining operation, such as finding the sum or maximum of a set of numbers, or
accumulating elements into a list.
radius=3
radius=5
radius=5
Total area = 27 +75 + 75 = 177
www.javathlon.com
REDUCING  THE  STREAM
i1 => radius=3 i2 => radius=5 i3 => radius=5
result = Initial
value
result = f(result, i1) result = f(result, i2) result = f(result, i3)
f(a, b) = a + (b.radius)*(b.radius)*PI
f(0, i1) = 0 + 3 *3 * 3 = 27
f(27, i2) = 27 + 5* 5*3 = 102
f(102, i3) = 102 + 5*5*3 = 177
www.javathlon.com
REDUCING  THE  STREAM
i1 => radius=3 i2 => radius=5 i3 => radius=5
result = Initial
value
result = f(result, i1) result = f(result, i2) result = f(result, i3)
stream. reduce(initial_value, f(a, b))
stream. reduce(0, (a,b) -> a + b * b * PI)
This would be enough if operations were sequential only. But
streams must be processable in parallel.
www.javathlon.com
PARALEL  REDUCING  OF  STREAM
✤ You must implement the reducing operation as parallel-ready.
✤ That’s why, reduce() method has a third parameter for combining the results of
parallel operations.
✤ Below code does not compile because JVM does not know what to do if stream is a
parallel stream. (a, b) -> a + b defines only the sequential reduce operation.
www.javathlon.com
PARALLEL  REDUCE  STREAM
✤ The third parameter is the accumulator and defines how to combine the intermediate
results of several threads.
5
53Thread 1
Thread 2
0 0 + 3*3*PI = 27 27 + 5*5*PI =112
0 0 + 5 * 5 *PI =75
0 + 112 = 112
112 + 75 = 189
Combiner
function
0
www.javathlon.com
PARALLEL  REDUCE  STREAM
5
53Thread 1
Thread 2
0 0 + 3*3*PI = 27 27 + 5*5*PI =112
0 0 + 5 * 5 *PI =75
0 + 112 = 112
112 + 75 = 189
Combiner
function
0
Combiner function
Accumulator function
Initial seed for both functions
www.javathlon.com
OTHER  OPERATIONS
distinct()
Using equals() method of a class, filters
duplicate items
sorted(Comparator c) Using given Comparator, sorts the stream
count() Find the item count in stream
www.javathlon.com
COLLECTOR
✤ Collector is a reducer operation.
✤ Reducer: takes a sequence of input elements and combines them into a single
summary result
✤ Result may be one single collection or any type of one object instance
www.javathlon.com
WHAT  COLLECTOR  DOES
radius=3
radius=5
radius=5
Total area = 27 +75 + 75 = 177
✤ Gets the desired values of each item, process and returns a single result
www.javathlon.com
WHAT  COLLECTOR  DOES
radius=3
radius=5
radius=5
✤ Converts the stream into a collection (List, Set, Map).
A list as output
www.javathlon.com
COLLECTORS
interface Collector<T,A,R> {
Supplier<A> supplier()
BiConsumer<A,T> accumulator()
BinaryOperator<A> combiner()
Function<A,R> finisher()
Set<Characteristics> characteristics()
}
supplier: starting object
accumulator: - mutable data structure that we will use to
accumulate input elements of type T.
combiner: used to join two accumulators together into one.
used in parallel mode.
finisher: takes an accumulator A and turns it into a result
value
www.javathlon.com
COLLECTORS.TOLIST()
Combiner function
Accumulator function
Initial seed for both functions
✤ Collectors.toList() collector
✤ Starts with an empty ArrayList
✤ Append each item to this ArrayList in sequential mode
✤ Add each intermediate ArrayList to total ArrayList while combining the results
www.javathlon.com
COLLECTORS
✤ Prebuilt Collector implementations that perform common tasks:
✤ Collectors.toList() Puts items into a list
✤ Collectors.toCollection(TreeSet::new) Puts items into a desired container. Container is supplied
with a supplier
✤ Collectors.joining(", “) Joins multiple items into a single item by concatenating
them
✤ Collectors.summingInt(item::getAge) Sums the values of each item with given supplier
✤ Collectors.groupingBy() Groups the items with given classifier and mapper
✤ Collectors.partitioningBy() Partitions the items with given predicate and mapper
www.javathlon.com
EXAMPLE
Salary:1000
Department: HR
Salary:3000
Department: Admin
Salary: 5000
Department:Admin
Salary:2000
Department: HR
Salary:3000
Department: Admin
Salary: 5000
Department:Admin
Salary:1000
Department: HR
Salary:2000
Department: HR
4000
4000
partioningBy
Find average
salary of
each
department
averagingInt
www.javathlon.com
RESULT  OF  GROUPING  BY
Salary:3000
Department: Admin
Salary: 5000
Department:Admin
Salary:1000
Department: HR
Salary:2000
Department: HR
List<Employee> List<Employee>
Map<String, List<Employee>>
key
www.javathlon.com
PIPELINING  REDUCERS
Salary:4000
Salary: 5000Salary:3000
Salary:2000
Map<String, List<Employee>> Map<String, Double>>
5000.0 9000.0
groupingBy
summingDouble
www.javathlon.com
PEEKING  INTERMEDIATE  RESULTS
20
peek the result without waiting the
next operations
www.javathlon.com
PEEKING  ELEMENTS
✤ In any intermediate operation, you may get the intermediate result.
✤ Below code, adds each item in stream after they are multiplied by two.
www.javathlon.com
CLOSURE
✤ Closure means that, if a method contains another method; outer variables should
be accessible to the inner method.
Image is from:
http://stackoverflow.com/questions/36636/what-is-a-closure
www.javathlon.com
CLOSURE  IN  JAVA  8
✤ A lambda expression is a function. So A lambda expression should be able to access
the variables in outer scope
✤ We may access but only if this variable is final (read-only)
www.javathlon.com
CLOSURE  IN  JAVA  8
✤ What if I really want to modify the local variable?
✤ You may use Atomic classes from Java 7.
PARALLELISM
Automa?c  usage  of  fork-­‐join  framework
www.javathlon.com
PARALLEL  STREAMS
✤ Parallel streams automatically
distribute the tasks to several
cores and combine the results
by using fork-join framework.
www.javathlon.com
PARALLEL  STREAMS  BENCHMARKING
✤ Benchmarking is done by JMH library.
✤ JMH library warms up the JVM with 10 iterations and then 10 real iteration.
✤ Calculates in one second, how many times this method can be completed. Because
I have selected the output type as “throughput”.
✤ The only difference in compared codes is the sequential stream processing and
parallel stream processing.
www.javathlon.com
PARALLEL  PROCESSING
JMH result Type Score Error Units
Sequential throughput 0.711 ± 0.011 ops/sec
Parallel throughput 2.260 ± 0.424 ops/sec
Parallel stream
operated 3 times
faster with 2 billion
items.
www.javathlon.com
PARALLEL  PROCESSING
JMH result Type Score Error Units
Sequential throughput 0.526 ± 0.006 ops/sec
Parallel throughput 1.845 ± 0.054 ops/sec
max() operation
also operated 3
times faster in
parallel mode
with 2 billion
items.
www.javathlon.com
IS  IT  ALWAYS  THAT  GOOD?
✤ If item count is not that
big, overhead of
parallel processing kick
offs will decrease the
overall performance. In
this code, parallel
processing is 3 times
slower than the
sequential one with
only 2000 items.
JMH result Type Score Error Units
Sequential throughput 106058.484 ± 1128.029 ops/sec
Parallel throughput 33520.489 ± 2358.957 ops/sec
www.javathlon.com
.parallel()  miracle?
✤ You invoke parallel() method on the stream and expected a true and faster process.
If so, you will be miserable.
✤ You must first
✤ transform your code into thread-safe structure.
✤ reduce blocking parts of the code
✤ obey the rules of monads in your code
www.javathlon.com
PARALLEL  PROCESSING  and  NON-­‐
DETERMINISM
Radius=10
Filter blues
Get radius of
first element
Radius=3
Filter blues
Get radius of
first element
✤ First execution ✤ Second execution✤ Encounter order and
output order of an item
may differ from time to
time if we are processing
in parallel.
✤ Stream structure
guarantees the latest
output’s order but not
the intermediate results
www.javathlon.com
PARALLEL  STREAM  BENCHMARKING
Type Score Error Units
Sequential throughput 0.090 ± 0.007 ops/sec
Parallel throughput 0.025 ± 0.003 ops/sec
✤ Parallel processing is 4
times slower unexpectedly.
Because underlying fork-join
framework has an overhead
when starting the threads.
And the operation on each
item costs a negligible time.
That’s why overhead slows
the process down.
www.javathlon.com
PARALLELISM  ON  CPU-­‐BOUND  
OPERATIONS
Score Error Units
Sequential 0.085 ± 0.003 ops/sec
Parallel 0.258 ± 0.008 ops/sec
Now, parallel processing is
faster.
Because the process time
on each item is much more
than fork-join overhead.
www.javathlon.com
CONCLUSION  -­‐  WHEN  TO  GO  PARALLEL?
✤ If our process is not IO-bound.
✤ If process for each item is CPU-bound and
✤ If duration of each process * item count > fork-join overhead
✤ Benchmark your operations before going parallel.
www.javathlon.com
PARALLELISM  ON  STATEFUL  OPERATIONS
Stateful operations
such as distinct and
sort harms
parallelism.
Score Error Units
Sequential 0.008 ± 0.001 ops/sec
Parallel 0.008 ± 0.002 ops/sec
www.javathlon.com
CONCLUSION  -­‐  WHEN  TO  GO  PARALLEL?
✤ If most of the operations are stateless such as map and filter. If sort, distinct
methods are used, multiple passes or data caching will be required. Bad for
parallelism because laziness can not be leveraged.
✤ When source collection is efficiently splittable such as ArrayList or Array.
Ad

Recommended

Clean Pragmatic Architecture - Avoiding a Monolith
Clean Pragmatic Architecture - Avoiding a Monolith
Victor Rentea
 
Intro to functional programming
Intro to functional programming
Assaf Gannon
 
GraalVM Overview Compact version
GraalVM Overview Compact version
scalaconfjp
 
Don't Be Mocked by your Mocks - Best Practices using Mocks
Don't Be Mocked by your Mocks - Best Practices using Mocks
Victor Rentea
 
Spring Boot
Spring Boot
Jiayun Zhou
 
Clean code and Code Smells
Clean code and Code Smells
Mario Sangiorgio
 
Functional Domain Modeling - The ZIO 2 Way
Functional Domain Modeling - The ZIO 2 Way
Debasish Ghosh
 
2 ways to get total sum of interactive grid column oracle apex ontoor blogs
2 ways to get total sum of interactive grid column oracle apex ontoor blogs
sulimankareem
 
Spring boot
Spring boot
sdeeg
 
React & GraphQL
React & GraphQL
Nikolas Burk
 
Clean code
Clean code
Mahmoud Zizo
 
The Art of Clean code
The Art of Clean code
Victor Rentea
 
Evolving a Clean, Pragmatic Architecture - A Craftsman's Guide
Evolving a Clean, Pragmatic Architecture - A Craftsman's Guide
Victor Rentea
 
啟動 Laravel 與環境設定
啟動 Laravel 與環境設定
Shengyou Fan
 
Clean Code - The Next Chapter
Clean Code - The Next Chapter
Victor Rentea
 
Spring boot Introduction
Spring boot Introduction
Jeevesh Pandey
 
Java 8 lambda
Java 8 lambda
Manav Prasad
 
Groovy presentation
Groovy presentation
Manav Prasad
 
Asynchronous JavaScript Programming
Asynchronous JavaScript Programming
Haim Michael
 
Hibernate Presentation
Hibernate Presentation
guest11106b
 
JavaScript Tutorial
JavaScript Tutorial
Bui Kiet
 
Clean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflix
Victor Rentea
 
Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & Streams
NewCircle Training
 
Introduction to Spring Boot!
Introduction to Spring Boot!
Jakub Kubrynski
 
Js: master prototypes
Js: master prototypes
Barak Drechsler
 
Clean Code
Clean Code
Dmytro Turskyi
 
JavaScript Promises
JavaScript Promises
Derek Willian Stavis
 
Domain Driven Design with the F# type System -- F#unctional Londoners 2014
Domain Driven Design with the F# type System -- F#unctional Londoners 2014
Scott Wlaschin
 
Java 8-streams-collectors-patterns
Java 8-streams-collectors-patterns
José Paumard
 
Functional Programming in JAVA 8
Functional Programming in JAVA 8
Ignasi Marimon-Clos i Sunyol
 

More Related Content

What's hot (20)

Spring boot
Spring boot
sdeeg
 
React & GraphQL
React & GraphQL
Nikolas Burk
 
Clean code
Clean code
Mahmoud Zizo
 
The Art of Clean code
The Art of Clean code
Victor Rentea
 
Evolving a Clean, Pragmatic Architecture - A Craftsman's Guide
Evolving a Clean, Pragmatic Architecture - A Craftsman's Guide
Victor Rentea
 
啟動 Laravel 與環境設定
啟動 Laravel 與環境設定
Shengyou Fan
 
Clean Code - The Next Chapter
Clean Code - The Next Chapter
Victor Rentea
 
Spring boot Introduction
Spring boot Introduction
Jeevesh Pandey
 
Java 8 lambda
Java 8 lambda
Manav Prasad
 
Groovy presentation
Groovy presentation
Manav Prasad
 
Asynchronous JavaScript Programming
Asynchronous JavaScript Programming
Haim Michael
 
Hibernate Presentation
Hibernate Presentation
guest11106b
 
JavaScript Tutorial
JavaScript Tutorial
Bui Kiet
 
Clean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflix
Victor Rentea
 
Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & Streams
NewCircle Training
 
Introduction to Spring Boot!
Introduction to Spring Boot!
Jakub Kubrynski
 
Js: master prototypes
Js: master prototypes
Barak Drechsler
 
Clean Code
Clean Code
Dmytro Turskyi
 
JavaScript Promises
JavaScript Promises
Derek Willian Stavis
 
Domain Driven Design with the F# type System -- F#unctional Londoners 2014
Domain Driven Design with the F# type System -- F#unctional Londoners 2014
Scott Wlaschin
 
Spring boot
Spring boot
sdeeg
 
The Art of Clean code
The Art of Clean code
Victor Rentea
 
Evolving a Clean, Pragmatic Architecture - A Craftsman's Guide
Evolving a Clean, Pragmatic Architecture - A Craftsman's Guide
Victor Rentea
 
啟動 Laravel 與環境設定
啟動 Laravel 與環境設定
Shengyou Fan
 
Clean Code - The Next Chapter
Clean Code - The Next Chapter
Victor Rentea
 
Spring boot Introduction
Spring boot Introduction
Jeevesh Pandey
 
Groovy presentation
Groovy presentation
Manav Prasad
 
Asynchronous JavaScript Programming
Asynchronous JavaScript Programming
Haim Michael
 
Hibernate Presentation
Hibernate Presentation
guest11106b
 
JavaScript Tutorial
JavaScript Tutorial
Bui Kiet
 
Clean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflix
Victor Rentea
 
Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & Streams
NewCircle Training
 
Introduction to Spring Boot!
Introduction to Spring Boot!
Jakub Kubrynski
 
Domain Driven Design with the F# type System -- F#unctional Londoners 2014
Domain Driven Design with the F# type System -- F#unctional Londoners 2014
Scott Wlaschin
 

Viewers also liked (20)

Java 8-streams-collectors-patterns
Java 8-streams-collectors-patterns
José Paumard
 
Functional Programming in JAVA 8
Functional Programming in JAVA 8
Ignasi Marimon-Clos i Sunyol
 
Ch1 Algorthmique Avancée - Rappel & Notions de Base
Ch1 Algorthmique Avancée - Rappel & Notions de Base
lotfibenromdhane
 
Ch3 Algorthmique Avancée - Méthodes Récursives
Ch3 Algorthmique Avancée - Méthodes Récursives
lotfibenromdhane
 
Functional Programming in Java
Functional Programming in Java
Premanand Chandrasekaran
 
Ch5 Algorthmique Avancée - Algorithme de Tri
Ch5 Algorthmique Avancée - Algorithme de Tri
lotfibenromdhane
 
Ch7 algorithmes NP-Copmlétude
Ch7 algorithmes NP-Copmlétude
lotfibenromdhane
 
Ch2 Algorthmique Avancée - Récursivité
Ch2 Algorthmique Avancée - Récursivité
lotfibenromdhane
 
Functional programming in java
Functional programming in java
John Ferguson Smart Limited
 
Notifications
Notifications
Youssef ELBOUZIANI
 
Java 8 Stream API and RxJava Comparison
Java 8 Stream API and RxJava Comparison
José Paumard
 
Database structure Structures Link list and trees and Recurison complete
Database structure Structures Link list and trees and Recurison complete
Adnan abid
 
Ch4 Algorthmique Avancée - Analyse & complexité des Algorithmes
Ch4 Algorthmique Avancée - Analyse & complexité des Algorithmes
lotfibenromdhane
 
Cats
Cats
Riadh Harizi
 
JDK 8, lambdas, streams, collectors - Bretagne Tour
JDK 8, lambdas, streams, collectors - Bretagne Tour
José Paumard
 
Java 8, Streams & Collectors, patterns, performances and parallelization
Java 8, Streams & Collectors, patterns, performances and parallelization
José Paumard
 
Functional programming with Java 8
Functional programming with Java 8
LivePerson
 
Alphorm.com Formation Autodesk Revit 2018 : Les nouveautés
Alphorm.com Formation Autodesk Revit 2018 : Les nouveautés
Alphorm
 
Alphorm.com Formation Java Server Faces
Alphorm.com Formation Java Server Faces
Alphorm
 
Alphorm.com Formation CND 2/2: Réussir la certification
Alphorm.com Formation CND 2/2: Réussir la certification
Alphorm
 
Java 8-streams-collectors-patterns
Java 8-streams-collectors-patterns
José Paumard
 
Ch1 Algorthmique Avancée - Rappel & Notions de Base
Ch1 Algorthmique Avancée - Rappel & Notions de Base
lotfibenromdhane
 
Ch3 Algorthmique Avancée - Méthodes Récursives
Ch3 Algorthmique Avancée - Méthodes Récursives
lotfibenromdhane
 
Ch5 Algorthmique Avancée - Algorithme de Tri
Ch5 Algorthmique Avancée - Algorithme de Tri
lotfibenromdhane
 
Ch7 algorithmes NP-Copmlétude
Ch7 algorithmes NP-Copmlétude
lotfibenromdhane
 
Ch2 Algorthmique Avancée - Récursivité
Ch2 Algorthmique Avancée - Récursivité
lotfibenromdhane
 
Java 8 Stream API and RxJava Comparison
Java 8 Stream API and RxJava Comparison
José Paumard
 
Database structure Structures Link list and trees and Recurison complete
Database structure Structures Link list and trees and Recurison complete
Adnan abid
 
Ch4 Algorthmique Avancée - Analyse & complexité des Algorithmes
Ch4 Algorthmique Avancée - Analyse & complexité des Algorithmes
lotfibenromdhane
 
JDK 8, lambdas, streams, collectors - Bretagne Tour
JDK 8, lambdas, streams, collectors - Bretagne Tour
José Paumard
 
Java 8, Streams & Collectors, patterns, performances and parallelization
Java 8, Streams & Collectors, patterns, performances and parallelization
José Paumard
 
Functional programming with Java 8
Functional programming with Java 8
LivePerson
 
Alphorm.com Formation Autodesk Revit 2018 : Les nouveautés
Alphorm.com Formation Autodesk Revit 2018 : Les nouveautés
Alphorm
 
Alphorm.com Formation Java Server Faces
Alphorm.com Formation Java Server Faces
Alphorm
 
Alphorm.com Formation CND 2/2: Réussir la certification
Alphorm.com Formation CND 2/2: Réussir la certification
Alphorm
 
Ad

Similar to Functional programming with Java 8 (20)

Functional programming principles and Java 8
Functional programming principles and Java 8
Dragos Balan
 
Fun with java 8
Fun with java 8
Victor Perepelitsky
 
Introduction to Functional Programming
Introduction to Functional Programming
Dave Fancher
 
Functional Programming in Java
Functional Programming in Java
Narendran Solai Sridharan
 
A Functional Approach to Java: Augmenting Object-Oriented Java Code with Func...
A Functional Approach to Java: Augmenting Object-Oriented Java Code with Func...
romergalbowx
 
Functional Programming 101 for Java 7 Developers
Functional Programming 101 for Java 7 Developers
Jayaram Sankaranarayanan
 
The joy of functional programming
The joy of functional programming
Steve Zhang
 
Why functional programming in C# & F#
Why functional programming in C# & F#
Riccardo Terrell
 
2014 java functional
2014 java functional
Demian Neidetcher
 
When life gives you functions make functional programs!
When life gives you functions make functional programs!
Aaron Levin
 
Functional Programming In Java Harnessing The Power Of Java 8 Lambda Expressi...
Functional Programming In Java Harnessing The Power Of Java 8 Lambda Expressi...
coriehokitiw
 
Intro f# functional_programming
Intro f# functional_programming
Mauro Ghiani
 
Functional JavaScript Fundamentals
Functional JavaScript Fundamentals
Srdjan Strbanovic
 
Lambdas, Collections Framework, Stream API
Lambdas, Collections Framework, Stream API
Prabu U
 
Insight into java 1.8, OOP VS FP
Insight into java 1.8, OOP VS FP
Syed Awais Mazhar Bukhari
 
Why should a Java programmer shifts towards Functional Programming Paradigm
Why should a Java programmer shifts towards Functional Programming Paradigm
Tech Triveni
 
Introduction Functional Programming - Tech Hangout #11 - 2013.01.16
Introduction Functional Programming - Tech Hangout #11 - 2013.01.16
Innovecs
 
Introductory func prog
Introductory func prog
Oleksandr Khomenko
 
Functional Programming in Swift
Functional Programming in Swift
Saugat Gautam
 
Scala: functional programming for the imperative mind
Scala: functional programming for the imperative mind
Sander Mak (@Sander_Mak)
 
Functional programming principles and Java 8
Functional programming principles and Java 8
Dragos Balan
 
Introduction to Functional Programming
Introduction to Functional Programming
Dave Fancher
 
A Functional Approach to Java: Augmenting Object-Oriented Java Code with Func...
A Functional Approach to Java: Augmenting Object-Oriented Java Code with Func...
romergalbowx
 
Functional Programming 101 for Java 7 Developers
Functional Programming 101 for Java 7 Developers
Jayaram Sankaranarayanan
 
The joy of functional programming
The joy of functional programming
Steve Zhang
 
Why functional programming in C# & F#
Why functional programming in C# & F#
Riccardo Terrell
 
When life gives you functions make functional programs!
When life gives you functions make functional programs!
Aaron Levin
 
Functional Programming In Java Harnessing The Power Of Java 8 Lambda Expressi...
Functional Programming In Java Harnessing The Power Of Java 8 Lambda Expressi...
coriehokitiw
 
Intro f# functional_programming
Intro f# functional_programming
Mauro Ghiani
 
Functional JavaScript Fundamentals
Functional JavaScript Fundamentals
Srdjan Strbanovic
 
Lambdas, Collections Framework, Stream API
Lambdas, Collections Framework, Stream API
Prabu U
 
Why should a Java programmer shifts towards Functional Programming Paradigm
Why should a Java programmer shifts towards Functional Programming Paradigm
Tech Triveni
 
Introduction Functional Programming - Tech Hangout #11 - 2013.01.16
Introduction Functional Programming - Tech Hangout #11 - 2013.01.16
Innovecs
 
Functional Programming in Swift
Functional Programming in Swift
Saugat Gautam
 
Scala: functional programming for the imperative mind
Scala: functional programming for the imperative mind
Sander Mak (@Sander_Mak)
 
Ad

Recently uploaded (20)

Introduction to sensing and Week-1.pptx
Introduction to sensing and Week-1.pptx
KNaveenKumarECE
 
May 2025: Top 10 Read Articles in Data Mining & Knowledge Management Process
May 2025: Top 10 Read Articles in Data Mining & Knowledge Management Process
IJDKP
 
Introduction to Natural Language Processing - Stages in NLP Pipeline, Challen...
Introduction to Natural Language Processing - Stages in NLP Pipeline, Challen...
resming1
 
Proposal for folders structure division in projects.pdf
Proposal for folders structure division in projects.pdf
Mohamed Ahmed
 
IPL_Logic_Flow.pdf Mainframe IPLMainframe IPL
IPL_Logic_Flow.pdf Mainframe IPLMainframe IPL
KhadijaKhadijaAouadi
 
AI_Presentation (1). Artificial intelligence
AI_Presentation (1). Artificial intelligence
RoselynKaur8thD34
 
Tally.ERP 9 at a Glance.book - Tally Solutions .pdf
Tally.ERP 9 at a Glance.book - Tally Solutions .pdf
Shabista Imam
 
special_edition_using_visual_foxpro_6.pdf
special_edition_using_visual_foxpro_6.pdf
Shabista Imam
 
How to Un-Obsolete Your Legacy Keypad Design
How to Un-Obsolete Your Legacy Keypad Design
Epec Engineered Technologies
 
Learning – Types of Machine Learning – Supervised Learning – Unsupervised UNI...
Learning – Types of Machine Learning – Supervised Learning – Unsupervised UNI...
23Q95A6706
 
Tesla-Stock-Analysis-and-Forecast.pptx (1).pptx
Tesla-Stock-Analysis-and-Forecast.pptx (1).pptx
moonsony54
 
(Continuous Integration and Continuous Deployment/Delivery) is a fundamental ...
(Continuous Integration and Continuous Deployment/Delivery) is a fundamental ...
ketan09101
 
Cadastral Maps
Cadastral Maps
Google
 
Modern multi-proposer consensus implementations
Modern multi-proposer consensus implementations
François Garillot
 
Abraham Silberschatz-Operating System Concepts (9th,2012.12).pdf
Abraham Silberschatz-Operating System Concepts (9th,2012.12).pdf
Shabista Imam
 
Deep Learning for Image Processing on 16 June 2025 MITS.pptx
Deep Learning for Image Processing on 16 June 2025 MITS.pptx
resming1
 
Decoding Kotlin - Your Guide to Solving the Mysterious in Kotlin - Devoxx PL ...
Decoding Kotlin - Your Guide to Solving the Mysterious in Kotlin - Devoxx PL ...
João Esperancinha
 
A Cluster-Based Trusted Secure Multipath Routing Protocol for Mobile Ad Hoc N...
A Cluster-Based Trusted Secure Multipath Routing Protocol for Mobile Ad Hoc N...
IJCNCJournal
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
djiceramil
 
Structured Programming with C++ :: Kjell Backman
Structured Programming with C++ :: Kjell Backman
Shabista Imam
 
Introduction to sensing and Week-1.pptx
Introduction to sensing and Week-1.pptx
KNaveenKumarECE
 
May 2025: Top 10 Read Articles in Data Mining & Knowledge Management Process
May 2025: Top 10 Read Articles in Data Mining & Knowledge Management Process
IJDKP
 
Introduction to Natural Language Processing - Stages in NLP Pipeline, Challen...
Introduction to Natural Language Processing - Stages in NLP Pipeline, Challen...
resming1
 
Proposal for folders structure division in projects.pdf
Proposal for folders structure division in projects.pdf
Mohamed Ahmed
 
IPL_Logic_Flow.pdf Mainframe IPLMainframe IPL
IPL_Logic_Flow.pdf Mainframe IPLMainframe IPL
KhadijaKhadijaAouadi
 
AI_Presentation (1). Artificial intelligence
AI_Presentation (1). Artificial intelligence
RoselynKaur8thD34
 
Tally.ERP 9 at a Glance.book - Tally Solutions .pdf
Tally.ERP 9 at a Glance.book - Tally Solutions .pdf
Shabista Imam
 
special_edition_using_visual_foxpro_6.pdf
special_edition_using_visual_foxpro_6.pdf
Shabista Imam
 
Learning – Types of Machine Learning – Supervised Learning – Unsupervised UNI...
Learning – Types of Machine Learning – Supervised Learning – Unsupervised UNI...
23Q95A6706
 
Tesla-Stock-Analysis-and-Forecast.pptx (1).pptx
Tesla-Stock-Analysis-and-Forecast.pptx (1).pptx
moonsony54
 
(Continuous Integration and Continuous Deployment/Delivery) is a fundamental ...
(Continuous Integration and Continuous Deployment/Delivery) is a fundamental ...
ketan09101
 
Cadastral Maps
Cadastral Maps
Google
 
Modern multi-proposer consensus implementations
Modern multi-proposer consensus implementations
François Garillot
 
Abraham Silberschatz-Operating System Concepts (9th,2012.12).pdf
Abraham Silberschatz-Operating System Concepts (9th,2012.12).pdf
Shabista Imam
 
Deep Learning for Image Processing on 16 June 2025 MITS.pptx
Deep Learning for Image Processing on 16 June 2025 MITS.pptx
resming1
 
Decoding Kotlin - Your Guide to Solving the Mysterious in Kotlin - Devoxx PL ...
Decoding Kotlin - Your Guide to Solving the Mysterious in Kotlin - Devoxx PL ...
João Esperancinha
 
A Cluster-Based Trusted Secure Multipath Routing Protocol for Mobile Ad Hoc N...
A Cluster-Based Trusted Secure Multipath Routing Protocol for Mobile Ad Hoc N...
IJCNCJournal
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
djiceramil
 
Structured Programming with C++ :: Kjell Backman
Structured Programming with C++ :: Kjell Backman
Shabista Imam
 

Functional programming with Java 8

  • 2. www.javathlon.com GREATEST  UPDATE  TO  JAVA ✤ Inspired by JVM languages such as Scala and Clojure and frameworks like Guava. ✤ Rise of functional programming
  • 3. www.javathlon.com WHAT  IS  FUNCTIONAL  PROGRAMMING? ✤ A programming style that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data. ✤ f(x) = y g(f(x)) = z ✤ Based on lambda calculus. (Some inputs are transformed to some output without modifying the input) ✤ No iteration, no for loop, no variable.
  • 4. www.javathlon.com NO  ITERATION? ✤ What? Without a for loop, how I will process all elements of an ArrayList? ✤ Yes seems weird. You need to change your mindset. Mind bending at first.
  • 5. www.javathlon.com FUNCTION…  YOU  MEAN  METHOD??? ✤ No, I don’t mean the methods inside a class. ✤ FUNCTION IS NOT METHOD! ✤ Methods are not independent program units and they are bound to another context, like an object instance or class. ✤ Methods may depend upon values other than its arguments ✤ Methods may change the values of its arguments or some other static values. ✤ Pure functions are opposite.
  • 6. www.javathlon.com WHAT  IS  A  FUNCTION? ✤ Lives independently ✤ Does not depend to any value other than its arguments ✤ Output of a function is a value or another function ✤ Does not change any argument’s value or any other external value. (no side effects) ✤ Functions may be composed together regardless of the context
  • 7. www.javathlon.com WHAT  IS  FUNCTIONAL  PROGRAMMING ✤ Functions exist independently. Not bound to objects or classes ✤ Functions can not change the state of any object or value ✤ All values are immutable. Hates mutability! ✤ No iteration. Operations are done by recursion.
  • 8. www.javathlon.com Why  so  afraid  of  mutability? Did  you  ever  wonder  why  most   solutions  to  program  glitches  are  fixed   by  rebooting  your  computer  or   restarting  the  offending  application?     That’s  because  of  state.  The  program   has  corrupted  its  state.
  • 9. www.javathlon.com Why  so  afraid  of  mutability? ✤ Do you remember synchronised keyword, Barriers, Semaphores, Locks and their lack of sweetness? ✤ Have you ever scratched your hair because of deadlocks, thread starving, unexpected values of non-atomic object operations? ✤ We created the devil, intentionally, ourselves. We! Phew! Why?
  • 10. www.javathlon.com How  to  prevent  multithread  problems? ✤ Prevent mutability ✤ If mutability is important, put the synchronisation block in the object. ✤ Use AtomicInteger instead of Integer ✤ Use ConcurrentHashMap instead of HashMap…
  • 11. www.javathlon.com MULTICORE  SUPPORT  AND  THREAD   SYNCHRONIZATION  IN  JAVA ✤ Fork/Join for multicore in Java ✤ Thread and ThreadPool for multi-thread ✤ Leverage all cores of CPU. Distribute the tasks each core and then combine the results.
  • 12. www.javathlon.com BIG-­‐DATA  AND  MAP-­‐REDUCE ✤ Huge data is processed in chunks, each chunk yields an intermediate form of data. ✤ Intermediate data is combined into single result. ✤ None of the functions may affect each other but simply yield a single result without a side effect.
  • 14. www.javathlon.com BIGDATA  AND  MAP-­‐REDUCE ✤ Each operation must be an independent pure function. ✤ So, functional programming is cut out for these type of problems.
  • 15. www.javathlon.com TALHA OCAKÇI FUNCTIONAL OBJECT ORIENTED JAVA 8 Where is functions? Independent Bound to object or classes. Called as method. Functional interface (Seems independent but bound to object or class again) Value state Immutable Mutable Immutable if you desire Function chaining Yes Yes if in same instance Lambda functions may chain Synchronization and multicore support Great!!! Exist but really a cumbersome So much easy than Java 7.
  • 17. www.javathlon.com ELEMENTS  OF  FUNCTIONAL   PROGRAMMING ✤Immutable state (yes, get rid of mutable state, the evil.) ✤No side effects of function apply. (Input arguments are not modified) ✤No iteration. Only recursion ✤Function references and function compositions ✤Higher order functions(functions may be passed as arguments to other functions) and currying (partial evaluation) ✤Lazy evaluation of collections ✤No null value ✤Closure ✤Monad
  • 18. www.javathlon.com JAVA  8  PRETENDS  TO  BE  A  FUNCTIONAL   PROGRAMMING  LANGUAGE Attribute Java 8 Solution (or pretend to be a solution) Immutable state final keyword, Immutable collections (Collections.unmodifiableX). Both make the objects and the collection itself immutable. Declarative. Not imperative Use Streams No iteration. Only recursion No for loop on collections. Instead use Streams and its methods. Function references and function composition All FunctionalInterfaces such as Function, Predicate, Consumer, Supplier interfaces and lambda expressions.
  • 19. www.javathlon.com JAVA  8  FUNCTIONAL  PROGRAMMING   ELEMENTS Attribute Java 8 Solution (or pretend to be a solution) Higher order functions and currying Manuel implementation, no real built-in solution Lazy evaluation of collections take() method of Stream No null value Optional class Monad Stream and Optional … Function Chaining Built-in with Function interface Closure Only with final variables
  • 20. www.javathlon.com SUMMARY ✤ Java 8 brings functional programming elements into the language not in an academical and formal level but has a goodwill to have them ✤ Lambda expressions ✤ Stream ✤ @FunctionalInterface and some others…
  • 21. www.javathlon.com FINAL  -­‐  IMMUTABLE  OBJECTS ✤ final keyword makes what final? ✤ final Date d = new Date(); ✤ d = new Date() // legal? ✤ d.setTime(23234234); // legal?
  • 22. www.javathlon.com FINAL  IMMUTABLE  OBJECTS ✤ final only protects the address changes. Can not protect state modifications. ✤ You must explicitly protect attributes with private access modifier and then prevent setter methods. ✤ LocalDate is announced as immutable Date object in Java 8.
  • 23. www.javathlon.com FUNCTIONAL  INTERFACE ✤ Formal definition: Single Abstract Method interfaces ✤ An interface with only one abstract method. ✤ Function, BiFunction, Predicate, Supplier and Consumer interfaces are function interfaces that come or gain importance with Java 8. ✤ Known are Runnable interface with run() method; Comparable with compare() method.
  • 24. www.javathlon.com FUNCTIONAL  INTERFACES Interface Input Output Goal Function Single object of any type Single object of any type 1. Applying a logic 2. Logic chaining BiFunction Two objects of any type Single object of any type 1. Applying a logic 2. Logic chaining Predicate Single object of any type boolean Tests if a value conforms to a logic Consumer Single object of any type None Using a value and output some side effect Supplier None Single object of any type Create an object of desired type
  • 25. www.javathlon.com FUNCTION  INTERFACE ✤ Used for creating a an output object based on a given input and the logic and possibly chaining with other functions. ✤ A logic can be packaged as a variable.
  • 26. www.javathlon.com FUNCTION  INTERFACE ✤ Used for creating a an output object based on a given input and the logic and possibly chaining with other functions. public interface Function<T,R> Layers   Tools  that  allow   Layers   Tools  that  allow  Apply  logic   Chain   Compose   Unit   R apply(T t) Applies logic to T and returns an object of R andThen(Function after) First applies its logic then the logic provided by Function after compose(Function before) First applies before logic then its own logic identity() Returns its own input argument
  • 28. www.javathlon.com CHAINING  FUNCTION Find  word   count Number  to   string talha ocakci java 3 1 One We have 2 functions written before
  • 29. www.javathlon.com CHAINING  FUNCTION Find  word   count Number  to   string talha ocakci java One Compose them as returning the word count in a string as text
  • 30. www.javathlon.com CHAINING  FUNCTION Find  word   count Number  to   string talha ocakci java 3 1 One
  • 31. www.javathlon.com CHAINING  FUNCTION Simple Function invocation: findWordCount.apply(“talha ocakci java”) => 3 numberToString.apply(2) => “two” Function Chaining findWordCount.andThen(numberToString).apply(“talha ocakci java”) => “three” Find  word   count Number  to   string talha ocakci java 3 3 “three” andThen
  • 32. www.javathlon.com FUNCTION  CHAINING  RULE ✤ Output type of first function must be a super class or the same class of the input of second function’s input Find  word   count Number  to   string talha ocakci java 3 3 “three” andThen
  • 33. www.javathlon.com FUNCTION  CHAINING  RULE ✤ Otherwise ClassCastException is thrown. Uppercase   sentence Number  to   string talha ocakci TALHA OCAKCI ???? andThen TALHA OCAKCI
  • 34. www.javathlon.com PREDICATE ✤ Tests if a data conforms to some value or logic ? = is yellow true = valid false = not valid
  • 35. www.javathlon.com PREDICATE  INTERFACE ✤Tests if a data conforms to some value or logic ✤Logical operations can be used public interface Function<T,R> Layers   Tools  that  allow   Layers   Tools  that  allow  Test  data   or   Negate   and   boolean test(T t) Tests if t conforms to a logic and(Predicate otherPredicate) Logical and operation with another predicate or(Predicate otherPredicate) Logical or operation with another predicate negate() Logical not operation
  • 36. www.javathlon.com USING  PREDICATE ✤ First predicate tests if given string has word “Download” ✤ Second predicate tests if text’s length is less than 50.
  • 37. www.javathlon.com USING  PREDICATE ✤ specialWordChecker.test(“Download now”); ✤ returns true ✤ sizeChecker.test(“Download now”); ✤ returns true
  • 38. www.javathlon.com LOGICAL  OPERATIONS  ON  PREDICATE ✤ Check if the string has less than 50 characters and contains word download by using existing Predicates ✤ sizeChecker.and(specialWordChecker).test(“Download now”)
  • 39. www.javathlon.com SUPPLIER ✤ Supplies an instance of given type by constructor or some other ways. .
  • 40. www.javathlon.com SUPPLIER  INTERFACE T get() Supplies you a T instance ✤ Supplies an instance of given type buy constructor or some other ways.
  • 42. www.javathlon.com CONSUMER ✤ Gets an object, uses it but does not return a response. ✤ It possibly side-effects such as changing the value of the object or writing some output to somewhere. . write something to somewhere
  • 43. www.javathlon.com CONSUMER  INTERFACE void accept(T t) Uses instance t, modifies it if necessary Does something without returning an output void andThen(Consumer otherconsumer) chains consumers ✤ Gets an object, uses it but does not return a response. ✤ It possibly side-effects such as changing the value of the object or writing some output to somewhere.
  • 45. www.javathlon.com LAMBDA  EXPRESSIONS ✤ Simplifying the usage of Function, Predicate, Consumer, Supplier interfaces lambda expressions are used. ✤ All methods of these interfaces may be changed with these : -> ✤ This expression may be referred with the proper interface reference. ✤ JVM understands which method to use.
  • 46. www.javathlon.com CONVERTING  A  DEFINITION  TO  LAMBDA   EXPRESSION t -> t.contains(“Download”)
  • 47. www.javathlon.com VALID  LAMBDA  EXPRESSIONS (parameters) -> expression (List<String> list) -> list.isEmpty() (parameters) -> {return … ;} (int a, String b) -> { System.out.println(a); return b +a ; } }(parameters) -> statements (int a, int b) -> a * b (parameters) -> statements (int a, int b) -> {return a * b;}
  • 48. www.javathlon.com LAMBDA  EXPRESSIONS ✤ -> automatically detects the proper interface, according to the return value and then invokes the proper method. ✤ t -> t.contains(“Download”) ✤ Since right hand side returns a boolean, JVM understands that it should use a Predicate. So implicitly creates a Predicate and then invoke test() method.
  • 49. www.javathlon.com LAMBDA  EXPRESSIONS ✤ -> automatically detects the proper interface, according to the return value and then invokes the proper method. ✤ t -> System.out.println(“t + “is my string””) ✤ Since right hand side returns nothing, JVM implicitly creates a Consumer and invokes apply method automatically.
  • 50. www.javathlon.com LAMBDA  EXPRESSIONS ✤ -> automatically detects the proper interface, according to the return value and then invokes the proper method. ✤ t -> t * 3; ✤ Since right hand side accepts an input and returns a value, JVM implicitly creates a Function instance and invoke apply method automatically.
  • 51. www.javathlon.com REFERRING  TO  A  LAMBDA  EXPRESSION
  • 52. www.javathlon.com REFERENCING  TO  LAMBDA  EXPRESSION ✤ This fails because right hand side of lambda returns nothing. Then it is not a Function but Consumer. Thus, below reference is correct.
  • 54. www.javathlon.com FUNCTION  CURRYING ✤ Currying is evaluating function arguments one by one, producing a new function with one argument less on each step.
  • 55. www.javathlon.com METHOD  AND  CONSTRUCTOR   REFERENCES      (  ::  operators  ) ✤ You don’t have to write a function from scratch every time. You may refer to a method or constructor of a class or instance. ✤ :: operator is used for accessing static method of a class or an instance method
  • 56. www.javathlon.com AVOIDING  NULL ✤ Null is a value that is not actually a value. ✤ Hard to determine whether the value not present or just has no value ✤ Null is mentioned as “millon dollar mistake” ✤ Functional programming avoids null ✤ Instead, each language has a structure for determining if a reference holds a real value or not. ✤ It is Optional in Java.
  • 57. www.javathlon.com OPTIONAL ✤ In functional programming, we chain functions. If somewhere in the chain, null is obtained, NullPointerException may be thrown. ✤ Between the chain items, we should be able to check if a value present. ✤ This is done by ifPresent() method of an Optional instance. A value exists inside? Yes, take it No, do you want me to supply something else?
  • 58. www.javathlon.com OPTIONAL ✤ Optional<String> myOptional = Optional.of(“test”); ✤ This says, a string may exist inside. get it with get() method ✤ If a value presents get it, or supply it with something else getOrElse(Supplier s) ✤ Check if a value presents with isPresent() ✤ Do something if value presents ifPresent(Consumer consumer)
  • 60. www.javathlon.com TALHA OCAKÇI Collection Stream maker Collection+ + + Copy the reference and pass stream funnel one by one + ✤ Stream is the structure for processing a collection in functional style. ✤ Original collection is not modified. ✤ Stream may be processed only once. After getting an output you can not use it again. STREAM
  • 61. www.javathlon.com TALHA OCAKÇI Stream maker Filter reds Make them triangle with same area Filter small triangles Sum up circumferences 20 You may stop processing in any of these steps
  • 62. www.javathlon.com STREAM  IN  JAVA  8 Each of these boxes is an functional interface: Function, Mapper, Supplier, Consumer, Predicate Stream may be created with stream() method of Collection. 20
  • 63. www.javathlon.com INTERMEDIATE  AND  TERMINAL   OPERATIONS ✤ Intermediate operations yield a new Stream and you may pipeline(chain) the operations ✤ Terminal operations yield a result other than a stream: A list, Integer etc… ✤ After a terminal operation, you can not use the stream again and you can not pipeline another function. Intermediate operations Terminal operations
  • 64. www.javathlon.com INTERMEDIATE  OPERATIONS Stream Operation Goal Input filter Filter items according to a given predicate Predicate map Processes items and transforms Function limit Limit the results int sorted Sort items inside stream Comparator distinct Remove duplicate items according to equals method of the given type
  • 65. www.javathlon.com TERMINAL  OPERATIONS STREAM OPERATION GOAL INPUT forEach For every item, outputs something Consumer count Counts current items collect Reduces the stream into a desired collection
  • 66. www.javathlon.com INITIALIZE  A  STREAM ✤ You may initialise a stream by using ✤ An existing Collection’s stream() method ✤ From scratch
  • 67. www.javathlon.com CONVERTING  COLLECTIONS  TO  STREAM ✤ You may use stream() method of any collection. ✤ Original collection is not effected during the process ✤ You can’t process a stream after you get an output. Collection Stream maker +
  • 69. www.javathlon.com CREATE  STREAM  FROM  SCRATCH ✤ You may use of() method of stream. Put the values as comma separated. ✤ Use IntStream, DoubleStream, LongStream and range() method of them.
  • 70. www.javathlon.com FILTER ✤ Includes the items that conform to given Predicate and creates a new stream. ? = is yellow true = valid false = not valid
  • 71. www.javathlon.com MAP ✤ All items are converted to a new state or a new type. ✤ Logic is assigned with a Function.
  • 73. www.javathlon.com WHAT  IS  REDUCTION? ✤ A reduction operation (also called as fold) takes a sequence of input elements and combines them into a single summary result by repeated application of a combining operation, such as finding the sum or maximum of a set of numbers, or accumulating elements into a list. radius=3 radius=5 radius=5 Total area = 27 +75 + 75 = 177
  • 74. www.javathlon.com REDUCING  THE  STREAM i1 => radius=3 i2 => radius=5 i3 => radius=5 result = Initial value result = f(result, i1) result = f(result, i2) result = f(result, i3) f(a, b) = a + (b.radius)*(b.radius)*PI f(0, i1) = 0 + 3 *3 * 3 = 27 f(27, i2) = 27 + 5* 5*3 = 102 f(102, i3) = 102 + 5*5*3 = 177
  • 75. www.javathlon.com REDUCING  THE  STREAM i1 => radius=3 i2 => radius=5 i3 => radius=5 result = Initial value result = f(result, i1) result = f(result, i2) result = f(result, i3) stream. reduce(initial_value, f(a, b)) stream. reduce(0, (a,b) -> a + b * b * PI) This would be enough if operations were sequential only. But streams must be processable in parallel.
  • 76. www.javathlon.com PARALEL  REDUCING  OF  STREAM ✤ You must implement the reducing operation as parallel-ready. ✤ That’s why, reduce() method has a third parameter for combining the results of parallel operations. ✤ Below code does not compile because JVM does not know what to do if stream is a parallel stream. (a, b) -> a + b defines only the sequential reduce operation.
  • 77. www.javathlon.com PARALLEL  REDUCE  STREAM ✤ The third parameter is the accumulator and defines how to combine the intermediate results of several threads. 5 53Thread 1 Thread 2 0 0 + 3*3*PI = 27 27 + 5*5*PI =112 0 0 + 5 * 5 *PI =75 0 + 112 = 112 112 + 75 = 189 Combiner function 0
  • 78. www.javathlon.com PARALLEL  REDUCE  STREAM 5 53Thread 1 Thread 2 0 0 + 3*3*PI = 27 27 + 5*5*PI =112 0 0 + 5 * 5 *PI =75 0 + 112 = 112 112 + 75 = 189 Combiner function 0 Combiner function Accumulator function Initial seed for both functions
  • 79. www.javathlon.com OTHER  OPERATIONS distinct() Using equals() method of a class, filters duplicate items sorted(Comparator c) Using given Comparator, sorts the stream count() Find the item count in stream
  • 80. www.javathlon.com COLLECTOR ✤ Collector is a reducer operation. ✤ Reducer: takes a sequence of input elements and combines them into a single summary result ✤ Result may be one single collection or any type of one object instance
  • 81. www.javathlon.com WHAT  COLLECTOR  DOES radius=3 radius=5 radius=5 Total area = 27 +75 + 75 = 177 ✤ Gets the desired values of each item, process and returns a single result
  • 82. www.javathlon.com WHAT  COLLECTOR  DOES radius=3 radius=5 radius=5 ✤ Converts the stream into a collection (List, Set, Map). A list as output
  • 83. www.javathlon.com COLLECTORS interface Collector<T,A,R> { Supplier<A> supplier() BiConsumer<A,T> accumulator() BinaryOperator<A> combiner() Function<A,R> finisher() Set<Characteristics> characteristics() } supplier: starting object accumulator: - mutable data structure that we will use to accumulate input elements of type T. combiner: used to join two accumulators together into one. used in parallel mode. finisher: takes an accumulator A and turns it into a result value
  • 84. www.javathlon.com COLLECTORS.TOLIST() Combiner function Accumulator function Initial seed for both functions ✤ Collectors.toList() collector ✤ Starts with an empty ArrayList ✤ Append each item to this ArrayList in sequential mode ✤ Add each intermediate ArrayList to total ArrayList while combining the results
  • 85. www.javathlon.com COLLECTORS ✤ Prebuilt Collector implementations that perform common tasks: ✤ Collectors.toList() Puts items into a list ✤ Collectors.toCollection(TreeSet::new) Puts items into a desired container. Container is supplied with a supplier ✤ Collectors.joining(", “) Joins multiple items into a single item by concatenating them ✤ Collectors.summingInt(item::getAge) Sums the values of each item with given supplier ✤ Collectors.groupingBy() Groups the items with given classifier and mapper ✤ Collectors.partitioningBy() Partitions the items with given predicate and mapper
  • 86. www.javathlon.com EXAMPLE Salary:1000 Department: HR Salary:3000 Department: Admin Salary: 5000 Department:Admin Salary:2000 Department: HR Salary:3000 Department: Admin Salary: 5000 Department:Admin Salary:1000 Department: HR Salary:2000 Department: HR 4000 4000 partioningBy Find average salary of each department averagingInt
  • 87. www.javathlon.com RESULT  OF  GROUPING  BY Salary:3000 Department: Admin Salary: 5000 Department:Admin Salary:1000 Department: HR Salary:2000 Department: HR List<Employee> List<Employee> Map<String, List<Employee>> key
  • 88. www.javathlon.com PIPELINING  REDUCERS Salary:4000 Salary: 5000Salary:3000 Salary:2000 Map<String, List<Employee>> Map<String, Double>> 5000.0 9000.0 groupingBy summingDouble
  • 89. www.javathlon.com PEEKING  INTERMEDIATE  RESULTS 20 peek the result without waiting the next operations
  • 90. www.javathlon.com PEEKING  ELEMENTS ✤ In any intermediate operation, you may get the intermediate result. ✤ Below code, adds each item in stream after they are multiplied by two.
  • 91. www.javathlon.com CLOSURE ✤ Closure means that, if a method contains another method; outer variables should be accessible to the inner method. Image is from: http://stackoverflow.com/questions/36636/what-is-a-closure
  • 92. www.javathlon.com CLOSURE  IN  JAVA  8 ✤ A lambda expression is a function. So A lambda expression should be able to access the variables in outer scope ✤ We may access but only if this variable is final (read-only)
  • 93. www.javathlon.com CLOSURE  IN  JAVA  8 ✤ What if I really want to modify the local variable? ✤ You may use Atomic classes from Java 7.
  • 94. PARALLELISM Automa?c  usage  of  fork-­‐join  framework
  • 95. www.javathlon.com PARALLEL  STREAMS ✤ Parallel streams automatically distribute the tasks to several cores and combine the results by using fork-join framework.
  • 96. www.javathlon.com PARALLEL  STREAMS  BENCHMARKING ✤ Benchmarking is done by JMH library. ✤ JMH library warms up the JVM with 10 iterations and then 10 real iteration. ✤ Calculates in one second, how many times this method can be completed. Because I have selected the output type as “throughput”. ✤ The only difference in compared codes is the sequential stream processing and parallel stream processing.
  • 97. www.javathlon.com PARALLEL  PROCESSING JMH result Type Score Error Units Sequential throughput 0.711 ± 0.011 ops/sec Parallel throughput 2.260 ± 0.424 ops/sec Parallel stream operated 3 times faster with 2 billion items.
  • 98. www.javathlon.com PARALLEL  PROCESSING JMH result Type Score Error Units Sequential throughput 0.526 ± 0.006 ops/sec Parallel throughput 1.845 ± 0.054 ops/sec max() operation also operated 3 times faster in parallel mode with 2 billion items.
  • 99. www.javathlon.com IS  IT  ALWAYS  THAT  GOOD? ✤ If item count is not that big, overhead of parallel processing kick offs will decrease the overall performance. In this code, parallel processing is 3 times slower than the sequential one with only 2000 items. JMH result Type Score Error Units Sequential throughput 106058.484 ± 1128.029 ops/sec Parallel throughput 33520.489 ± 2358.957 ops/sec
  • 100. www.javathlon.com .parallel()  miracle? ✤ You invoke parallel() method on the stream and expected a true and faster process. If so, you will be miserable. ✤ You must first ✤ transform your code into thread-safe structure. ✤ reduce blocking parts of the code ✤ obey the rules of monads in your code
  • 101. www.javathlon.com PARALLEL  PROCESSING  and  NON-­‐ DETERMINISM Radius=10 Filter blues Get radius of first element Radius=3 Filter blues Get radius of first element ✤ First execution ✤ Second execution✤ Encounter order and output order of an item may differ from time to time if we are processing in parallel. ✤ Stream structure guarantees the latest output’s order but not the intermediate results
  • 102. www.javathlon.com PARALLEL  STREAM  BENCHMARKING Type Score Error Units Sequential throughput 0.090 ± 0.007 ops/sec Parallel throughput 0.025 ± 0.003 ops/sec ✤ Parallel processing is 4 times slower unexpectedly. Because underlying fork-join framework has an overhead when starting the threads. And the operation on each item costs a negligible time. That’s why overhead slows the process down.
  • 103. www.javathlon.com PARALLELISM  ON  CPU-­‐BOUND   OPERATIONS Score Error Units Sequential 0.085 ± 0.003 ops/sec Parallel 0.258 ± 0.008 ops/sec Now, parallel processing is faster. Because the process time on each item is much more than fork-join overhead.
  • 104. www.javathlon.com CONCLUSION  -­‐  WHEN  TO  GO  PARALLEL? ✤ If our process is not IO-bound. ✤ If process for each item is CPU-bound and ✤ If duration of each process * item count > fork-join overhead ✤ Benchmark your operations before going parallel.
  • 105. www.javathlon.com PARALLELISM  ON  STATEFUL  OPERATIONS Stateful operations such as distinct and sort harms parallelism. Score Error Units Sequential 0.008 ± 0.001 ops/sec Parallel 0.008 ± 0.002 ops/sec
  • 106. www.javathlon.com CONCLUSION  -­‐  WHEN  TO  GO  PARALLEL? ✤ If most of the operations are stateless such as map and filter. If sort, distinct methods are used, multiple passes or data caching will be required. Bad for parallelism because laziness can not be leveraged. ✤ When source collection is efficiently splittable such as ArrayList or Array.