Functional Programming is nothing new to the JVM. But with Java 8 it was the big change in paradigm for Java developers. Learn how switching from imperative to functional results in more maintainable code.
The presentation was given at tech meetup KrkDataLink, The missing link between Functional Programming and Data Science.
11. 11
Functional interface Function descriptor
Predicate<T> T -> boolean
Consumer<T> T -> void
Function<T,R> T -> R
Supplier<T> () -> T
UnaryOperator<T> T -> T
BinaryOperator<T> (T,T) -> T
BiPredicate<L,R> (L,R) -> boolean
BiConsumer<T,U> (T,U) -> void
BiFunction<T,U,R> (T,U) -> R
12. #instead of
Runnable task =
new Runnable() {
public void run() {
System.out.println(”no arg consumer” )
}
}
12
Replace ceremony with Lambda
Runnable task =
() -> { System.out.println(”no arg consumer” ); };
18. 18
Slimmer patterns: decorator
← https://en.wikipedia.org/wiki/Decorator_pattern#Second_example_.28coffee_making_scenario.29
← Hierarchy of types
can be replaced with Function Composition:
● .compose(Function f)
● .andThan(Function f)
19. 19
Function composition
class Barista {
public static Coffee makeCoffee
(Coffee baseCoffee,
Function<Coffee, Coffee>... addIngredients)
{
return Stream.of(addIngredients)
.reduce(
Function.<Coffee>identity(),
//or Function::andThan
(addIngr1, addIngr2) -> addIngr1.andThan(addIngr2))
Coffee coffee = Barista.makeCoffee(
new Arabica(),
Coffee::withMilk,
Coffee::withSprinkles));
20. Object vs Functional
20
● Imperative
● Mutability
● Lower abstraction
● Reveals impl. details
● Eager by default
● nulls
● Hierarchy of types
● Declarative
● Favors Immutability
● Expressive
● Hides impl. details
● Lazy by default
● Optionals
● Function composition