Java lambda and functional programming
Java lambda expressions are syntactical sugars, It is a way of reducing lines of coded. In other words, trim down the code and increase readability. In this blog, we will be discussing Java lambda and functional programming.
Lambda functions are used with functional interfaces in Java. There three important rules to write lambda.
The class/interface (1) should only one abstract method. The argument for the abstract method should match to lambda before arrow part(2). The return type(3) should match to abstract method return type.
Zero parameters is just an empty parenthesis. The function’s name and object doesn’t need to be the same, it can be different.
One parameter do not require parenthesis. There is a Java provided a standard interface for these kinds of interface, Which accepts and returns only one argument. Please check Functional<T,R> interface. With this standard interface, we don’t need to create any new interfaces anytime for any methods which accept and return only one variable.
Multiple parameters are enclosed in parenthesis. Function interface having method which accepts two parameters and returns one value are often called Two-Arity Functions. Here are the Java-defined interfaces for these kinds of methods.
ToIntBiFunction, ToDoubleBiFunction, ToIntBiFunction, and ToLongBiFunction
Multiple lines of code in functions body.
We add curly braces in case there are multiple lines in the body. It properly defines the starting and ending of the block.
Pass Lambda function as a variable.
With the functional interface and lambda expression in Java8 we can do the same.
Return Lambda function from the function
In the below example, we have a function which takes a string parameter and returns a method(functional interface).
There is a little more to lambda functions, Double colon operator. It looks something like this.
It might look a little bit confusing but it fairly simple and easy to understand. This is it on our Java lambda and functional programming - Part 2. Please check out next blog in this series Java 8 double colon operator.