What are lambda expressions :
How to use Java8 lambdas :
- Let’s look at an example of collection sorting: Collection.sort(List
list, Comparator c ) - In Java7, you could either create seperate class which implements Comparator interface or create an anonymous inner class. Both of these solutions are verbose and looks cumbersome. Here is an example of using anonymous inner class for sorting of cityList by their name lenghts :
Collections.sort(cityList, new Comparator(){
@Override
public int compare(String s1, String s2) {
return s1.length() - s2.length();
}
});
- The above code can be rewritten in Java8 using lambda expression as follows :
Collections.sort(cityList, (s1, s2) -> s1.length() - s2.length());
Writing lambda expressions :
- Lambda expression does not contain function declaration, name or a return type.
- It looks like a function. It’s input arguments need not have a type (but, you can supply one if you want).
- The type is inferred from context.
- The body of the function starts after the “->” sign
- If it is a simple/single line function then the keyword ‘return’ is not needed.
- If the body has a single statement (as in the example above), then, curly braces are not needed.
- If there is only a single input argument to the function, then, parenthesis are not needed.