Java 1.8 has brought with it important changes in our way of programming and specifically one of them is the so-called lambda expressions. These expressions greatly shorten the code of our application, but what implications does this really have for its performance?
- How do these types of expressions benefit or harm us and how does it affect the performance of the application?
- Can optimizing these expressions improve the performance of traditional code and really help reduce code?
Indeed, Lambda expressions, along with the Stream API, are the two most significant changes introduced in Java 8, as explained in this introductory document .
What are its benefits?
Here are some:
Without Lambda:
With Lambda:
the door is opened towards functional programming in Java, where functions play a fundamental role. This means being able to pass functions, at runtime, as variable values, return values, or parameters to other functions. This is a very powerful concept that can be understood as the ability to pass behavior as a value, and it is precisely what we can achieve by adding lambda expressions to the Java language.
By using them in combination with the Stream API, we will be able to perform filter/mapping/reduction type operations on data collections sequentially or in parallel and make their implementation transparent to the developer.
When the lambda expression is made up of a single statement and invokes some existing method by its name, there is the possibility of writing it using reference methods, which makes the code more compact and easier to read.
code writing is actually reduced. (See in this regard the example case raised in the article Introduction to Lambda Expressions
Does it have disadvantages?
Well, yes, it has one (although more than a disadvantage we can call it a challenge, the challenge of improving ourselves, of continuing to learn).
Learning to use Lambda expressions (as well as the Stream API) requires a paradigm shift in the way we've written Java code so far.
But overcoming that barrier has its reward, since we will have in our hands a very powerful tool that will make our lives easier.
Some examples to see the differences
1. Implementation of
Runnable
2. Event handling
3. Iterating over lists
4. Map and Reduce example
12% will be applied to the code on each purchase
Links