Monday, May 16, 2016

Lambda expressions: the easy way

With the introduction of Java 8, a key concept that came out was lambda expressions. It is a bit confusing at the start, but once you get the hang of it, it really simplifies the code. So here are few key points that helped me in understanding the concept of Lambda expressions.s

1. Behavior Parameterization

Behavior parameterization is the idea behind lambda expressions. That is now you can pass a code block as an argument to a method, just like you used to pass variables and objects.

2. Syntax of lambda

input parameters - > body of lambda  (expression/block of code)

The important thing to note here is , that if the body of lambda is an expression, it will return the value of the expression, hence you do not need to add keyword 'return'. However if you have a set of statements executed, then you need to add the keyword 'return' as well as an ending ';'.

for example,

 (int a, int b) -> a +b

(int a, int b) -> {
                           int c = a + b;
                           return c * a;
                        } ;

3. Functional interfaces

A functional interface is an interface that specifies only one abstract method.
Lambdas can be used in the context of functional interfaces. That is lambda expressions  can be treated as an instance of the mentioned functional interface, hence you do not need to specify the input parameter types.
For example if we consider 'Predicate' functional interface that is provided by Java, which returns a boolean value, we could write it like ,

Predicate<Person> p = (Person p1) -> p1.getAge();

also we could write it like ,
Predicate<Person> p = (p1) -> p1.getAge();

So there are a number of supported functional interfaces that are provided from Java, which you could check in [1] . However if you need to write your own custom functional interface, you could do it with the use of @Functional. This annotation is not mandatory, but it will throw an error if there is anything more than one abstract method defined.



No comments:

Post a Comment