Abstract
- A concise way to defining an implementation of a Functional Interface and obtain an OOP Object of that particular implementation
Why concise?
It allows us to create an implementation of a OOP Interface without the need to create an OOP Class or Anonymous Inner Class explicitly.
Attention
Can only be used in the context of Functional Interface, because Java lambda can only define the implementation of one OOP Abstract Method.
Important
Creating an illusion of First-class Citizen Function.
Java Lambda Showcase
- In the code editor below, we have a Functional Interface
Calculator
that has an OOP Abstract Methodcalculate
that takes in 2 parameters - There are 3 implementations of the functional interface in 3 different ways - standard OOP Class (
addCalculator
), Anonymous Inner Class (subtractionCalculator
) and Java Lambda (multiplyCalculator
)
- As you can see from the implementations from the code editor above, the implementation with java lambda syntax is much more concise, we are focused on the actual logic being implemented rather than the ceremony of defining interfaces and classes
- In another word, instead of creating a class that contains the implementation, we can create the implementation without the need to create a class. This enhance the functional programming capabilities of Java
Java Stream API
- A way to process a sequence of OOP Object using functional programming style
- In the code editor below, we have a Dynamic Array of integers. The stream API is carried in 4 steps:
- create a stream of the integer with
stream()
- multiply all the integers in the stream by with
map(num->num * 2)
- sort the the stream in ascending order with
sorted()
- print out the stream of integers with
forEach(num->System.out.println(num))
- create a stream of the integer with
Builder design pattern & Java Lambda
As you can see, the Java Stream API syntax is very concise, thanks to builder design pattern and Java Lambda.
The intermediate operations like
stream()
,sorted()
andmap()
follows the builder design pattern, returning a new object of stream after execution. This avoids the need to create variables to store intermediate processed results, making the code more concise.Java lambda allows us to specify the logic inside
.map()
and.forEach()
without the need to create OOP Class that contains the logic implementation explicitly, making the code more concise.