One of the most prominent and widely used languages in the world has Evolved.
Java ever gave us power on object oriented progrmming and we did the best we could with it.
Now there’s another new elegant way changing the java world-Lambda Expression, that will make our code more expressive, easier to write, less error prone, and easier to parallelize than has been the case with Java.
Lambda Expression
Let’s start from a simple example:
Suppose we’re asked to total the prices greater than $20, discounted by 10%. Let’s do that in the habitual Java way first.
Old way
1 2 3 4 5 6 7 8 9 10 11 |
|
A Better way
Now we can do better, a lot better. Our code can resemble the requirement specification. This will help reduce the gap between the business needs and the code that implements it, further reducing the chances of the requirements being misinterpreted.
1 2 3 4 5 6 7 |
|
Instead of explicitly iterating through the prices list, we’re using a few special methods:
- Using filter() to get the record we are interested
- Using map() to transfer to another result set
- Using reduce() to compute the total on the result
Summary
It’s a whole new world in Java. We can now program in an elegant and fluent functional style, with higher-order functions. This can lead to concise code that has fewer errors and is easier to understand, maintain, and parallelize.