Slides aim to provide constructed information about functional programming in Java 8. To able to do that, Lambdas, Built-in Functional Interfaces and Optionals summarised with code examples.
3. Writing Simple Lambdas
—> A lambda expression is a block of code that gets passed
around. A lambda expression can be thought as a continued
anonymous method. A lambda expression has parameters and a
body just like regular methods do, but it doesn’t have a name like
a real method.
5. Which Variables Can My
Lambda Access?
• Lambdas are allowed to access instance and static variables.
• Method parameters and local variables could be used if they
are not assigned new values. Finals and effectively final
variables.
6. Functional Interface
• A Functional Interface
has exactly one
abstract method.
• It could have any
numbers of default
methods.
7. Built-In Functional Interfaces
• Java 8 provides built-in functional interfaces in java.util.function
package.
Interface Parameters Return Type Method
Supplier<T> 0 T get
Consumer<T> 1(T) void accept
BiConsumer<T,U> 2(T,U) void accept
Predicate<T> 1(T) boolean test
BiPredicate<T> 2(T,U) boolean test
UnaryOperator<T> 1(T) T apply
BinaryOperator<T,T> 2(T,T) T apply
Function<T,R> 1(T) R apply
BiFunction<T,U,R> 2(T,U) R apply
8. Implementing Supplier
• Supplier interfaced is used when you want to
generate or supply values without taking
parameters.
• Related method name is get().
9. Implementing Consumers
• Consumer interfaces used when you want to do
something with parameter but not return
anything.
• Related method name is accept().
10. Implementing Predicates
• Predicates are often used for distinguishing
elements.
• Related method name is test(). And() and Negate()
are useful default methods.
14. Optionals
• An optional could have a value inside or not.
• Optional.empty() Optional.of()
100.0
15. Optional Methods
Method Optional Empty
Optional with
Value
get() Throws an Exception Returns value
ifPresent() Returns false Returns true
ifPresent(Consumer cons) Does nothing Calls consumer
orElse(T other)
Returns other
parameter
Returns value
orElseThrow(Supplier s)
Throws supplied
exception
Returns value
orElseGet(Supplier s)
Returns supplied
value
Returns value
16. Optional Methods
• Returning an optional instead of null is more clear
statement that tells there might be no value.
• Usage of sample methods on an empty optional
17. Thank You
References
OCA Oracle Certified Associate Java SE 8 Programmer I Study Guide
OCP Oracle Certified Professional Java SE 8 Programmer II Study Guide
You may reach piece of codes in the slides on Github page
https://github.com/AngelThread/Java8/tree/master/Functional_Programming_in_Java_8
Ugur Yeter
ytr.ugur@gmail.com
*Please do not hesitate to contact me if you have any questions related to slides