Sei sulla pagina 1di 2

Explaining Lambda expressions will be incomplete if I havent discussed about

Functional Programming. Functional Programming is the main reason for Lambda


expressions birth. Let us see what functional programming is.

In the programming world, function accomplishes all of the tasks but they are not
first class citizens like objects. In order to call a function you need an object and you
cannot pass function as you can pass an object. Functional programming is all about
making functions as first class citizens. i.e., functions should be able to
1. Accept the other functions as arguments. a.k.a behavioral parameterization
2. Create functions inside them
3. Return a function.
In order to achieve Functional Programming Lambda expressions are the Master Key.
Of course functional programming deals with some other features like promoting
immutability
Lets take an application and see how we can simplify the implementation using
Lambda expressions.
Your boss asked you to write a program to SUM the values in an array.
In traditional programming the following code will do the SUM.
Now your boss impressed by the code and asked to add some functionality by
finding the sum of even number. Then you have added another function which
calculates the sum of even numbers.

Again your boss asked you to add some other functionality by finding sum of odd
numbers. Again you created one more method to find sum of odd numbers.

If you observe the three code blocks, you repeated lot of code. DRY principle is not
followed. You are helpless here because you are not able to pass the behavior to the
function. If you are able to pass the behavior you needed to the function, with a
single method you can accomplish all of the three tasks.
Functional programming (or behavioral parameterization using Lambdas) will make
the above code concise, flexible and maintainable.
Now I am creating a method addSelected which will accept an array and a
Predicate<T>. Predicate<T> is a predefined functional interface in Java. Functional

interface is an interface which consists of only one abstract method. Predicate


interface has test method (abstract)

Now the method is ready. How will you find the Sum of all number by using above
function? The following code does the work.

Here we are passing a Lambda expression in place of Predicate. That means we are
providing the implementation of the test method.
Lambda expression can be passed to Functional Interface
We are able to pass the behavior to a function using the lambda expression. This is
the motivation behind the lambdas i.e., passing the behavior to a function.
The following code block will find the Sum of Even numbers and odd numbers.

Potrebbero piacerti anche