Lambda expressions are one of the more exciting features in Java 8. They are basically used to pass code instead of objects to a method or to deal with
group of data to execute algorithms. A Lambda Expression is a representation of an anonymous function which can be passed around as a parameter thus
achieving behavior parameterization. A lambda consists of a list of parameters, a body, a return type and a list of exceptions which can be
thrown. i.e. it is very much a function, just anonymous.
Let's check the structure of lambda expressions.
- A lambda expression can have zero, one or more parameters.
- Parameters are enclosed in parentheses and separated by commas. e.g. (x, y) or (int x, int y) or (String x, int y, float z)
- If body of lambda expression has single statement curly brackets are not mandatory and the return type of the anonymous function is the same as that of the body expression.
- The type of the parameters can be explicitly declared or it can be inferred from the context. e.g. (int x) is same as just (x)
- Declaring the types of the parameters is optional. Empty parentheses are used to represent an empty set of parameters. e.g. () -> 42
- The body of the lambda expressions can contain zero, one or more statements.
- When there is a single parameter, if its type is inferred, it is not mandatory to use parentheses. e.g. x -> return x*x
Why lambda ?
Here are some points for use Lambda :
- Enables Functional Programming
- Enable support for parallel processing
- Readable and concise code
- Easier to use APIs and libraries
When to use a lambda ?
Lambda is replacement of Anonymous class ? NO, Lambdas are anonymous functions which are designed to eliminate overhead (Constructor and other bulky code) of
Anonymous class where it is not required.
Anonymous class :
If you want to declare constructor, some variables and going to write additional methods that will not be part of Interface, Then use Anonymous class.
Lambda Expression Examples:
If you want to implement only method of functional interface, than use Lambda expressions or you want to pass that to other code.
Let see other lambda expression example, how will we use lambda expression with threads, collections and stream. I will discuss stream in other tutorial.