How to write Lambda Expression?
In this blog, I ll just try to explain the basic things i.e. how easy is it to write Lambda Expression but before starting with the syntax, Let’ see what is lambda Expression?
In simple term, Lambda expression (->) is an anonymous function which
- doesn’t have any name
- doesn’t have any modifiers
- doesn’t have any return type.
To understand it in a more easy way, Let’s first write a simple Java function which display some message on the console.
Example 1: Display Message
- public void display (){
- system.out.println(“Learning Lambda Expression”);
- }
Step 1: Delete public (Modifier) void (return type) and display ( function name) from first line.
public void display(){- system.out.println(“Learning Lambda Expression”);
- }
Step 2: Add Lambda Expression Symbol before curly braces.
() -> {system.out.println(“Learning Lambda Expression”);}
That’s it, We have converted the normal Java code into Lambda Expression form. Just delete the name, return type, modifier and add lambda expression symbol and you are done :)
Code Optimization: The above syntax is correct but we can optimize it further...
Rule 1: if the function body has only statement then we can remove the curly braces.
() -> system.out.println(“Learning Lambda Expression”);
Example 2: Addition of two numbers
- public void sum(int x, int y) {
- system.out.println(x+y);
- }
(int x, int y) -> system.out.println(x+y);
Isn’t it simple? Right?
Let's see the second rule
Rule 2: Use Parameter type Inference. If you don’t know what is Type Inference then you can read my blog over here. In one line, Type Inference is the ability of the compiler to look at the method and to guess the correct method invocation. So we can remove int type from method parameters.
(x, y) -> system.out.println(x+y);
Example 3: Returns the length of String
- public int getLength(String s){
- return s.length();
- }
(s) -> return s.length();
Rule 3: Again as per Type Inference, We can also ignore the return type over here as compiler can guess easily the return type.
(s) -> s.length();
Rule 4: if the function has single parameter then we can ignore it. So the final optimize and concise Lambda expression for Example 3 would be
s -> s.length();
That's it for now. Will try to cover other topics of JAVA 8 in my next blog.
Happy Coding...!!!
No comments:
Post a Comment