Java 8 Lambda Expression Features Tutorial Examples

1. Introduction On Java lambda expression

A Lambda expression is a new and most popular feature of Java, which was included in Java SE 8. It introduces new concept called “functional programming” in Java, which is a completely object-oriented and imperative programming language.

1.1 What are lambda expression in java?

A lambda expression is an anonymous(nameless) function which don’t have any name and does not belong to any class i.e it is a block of code that can be passed around to execute.

Note: Java lambda expression is treated as a function, so compiler does not create .class file.

1.2 Why lambda expression is popular in java 8?

Java lambda expression

A lambda expression is very popular in java 8 for the following reasons like,

  • It has rich library collection.
  • Java lambda expressions are commonly used to implement callbacks or event listeners in functional programming with java stream API.
  • A lambda expressions mainly helps in filter, iterate and extract data from collection.
  • It’s a clear and concise way to represent one method interface using an expression.
  • It reduces LOC (Lines of code) compare to previous java programs.
  • Lambda expressions are very popular for its compact code which is easier to read and follow.
  • A lambda expression provides in line performance and multi-core processing with streams API.
  • It improves the code quality of functional interface implementations in java 8.

1.3 Properties of java lambda expression

  • Anonymous : Java lambda is Anonymous in nature due to it’s nameless function. It does not have any name and does not belong to any class.
  • Function: Lambda expressions are called as a function because it is not related with a particular class. Lambda expression are treated like a method because it has arguments, return type and body. A possible list of exceptions can be thrown.
  • Passed around: A lambda expression can be passed as argument to a method.
  • Concise: A lambda expression represent lot of information clearly in few LOC (lines of code).

1.4 Functionalities of lambda expression in java 8

  • In lambda expression, it enable to treat functionality as a method argument or code as data.
  • In lambda expression function can be created without the ownership of any class.
  • A lambda expression can be passed around as if it was an object and executed on demand.

2. The  5 different syntax of lambda expression

Let’s understand the five different syntax of lambda expression along with an example.

1. Standard Syntax

Syntax:

(parameter-list) -> {body} 

Standard syntax of lambda expression contains three parts.

  • A list of parameter: It can be empty or non-empty as well.
  • Arrow-token: It is used to link parameter-list and body of expression.
  • body: It contains expressions and statements for lambda expression.

Example

In this example we are sorting the array based on the length using standard syntax.

standard example

2. Parameter deduce syntax

In this method parameter can be deduce from the context i.e type can be delete from the context.

Example

In the above example, the type of m and n can be inferred to String, so the type can be deleted. This makes the code cleaner and more like a real lambda expression.

parameter deduce syntax

3. Multiple Lines of Code in Lambda Expression

In this method code can be written in multiple lines, but it should be enclosed with in {} as well as code should clearly contain return statement.

Example

multiple lines of code

4. Single Parameter with Inferred Type

Here parenthesis are deleted for single parameter lambda expression when types can be inferred.

Example

Single Parameter with Inferred Type

5. Method References

In this method by using Method References we can modify the above code as shown in the below example.

Example

Method references

3. Lambda expression v/s method in Java

Lambda ExpressionMethods in java
* A Lambda expression has only two parts they are,

·         body

·         Parameter list.

 

* Lambda expression is an anonymous, it doesn’t care about the name.

 

*  Body is the main part of the function.

 

* Lambda expression does not contain return type because, in java 8 compilers are able to infer the return type by checking the code, so no need to mention.

 

 

* A method or function in Java has mainly four parts they are,

·         Name

·         Parameter list

·         Body

·         Return type.

4. Benefits of using lambda expression in Java 8

The main benefits of using lambda expression in java 8 are,

  • Less lines of code.
  • Backward compatibility
  • Higher Efficiency by Utilizing Multi-core CPU’s

Note: Lambdas provides backward compatible, we can use them in existing API when we migrate our project to java 8.

Let’s see the benefits along with an example programs one by one.

Example 1: Java Lambda Expression with no parameter.

In this example we can see a method with no parameter.

Method with no parameter example

Example 2: Java Lambda Expression with single parameter.

In this example we can see a method with single parameter called as “num”.

single parameter example

Example 3: Java Lambda Expression with Multiple Parameters.

In this example we can see a method with multiple parameters or arguments.

Multiple Parameters example

Example 4: Iterating collections using forEach loop.

In this example we can see Iterating collection of names using forEach loop.

Iterating collections example

 

Example 5: Java Lambda Expression without creating anonymous inner class.

In this example without using anonymous inner class we have implemented abstract method of functional interface with few LOC (lines of code) .

Lambda expression

5. Use cases of Java 8 lambda expression

Let’s have a look on use case examples of java 8 lambda expression.

1. Java 8 lambda expression are mainly used to execute a block of code later, once or multiple times.

2. In Boolean expressions we can use lambda expression.

Example: (List list) -> list.isEmpty()

3. Using lambda expression we can Create a new objects.

Example: () -> new pet(“dog”, 13)

4. we can also used as consuming from an object.

Example: (Pet p) -> { System.out.println(p.getAgeMonths()); }

5. A lambda expression used to Select or extract from an object.

Example: (String s) -> s.length()

6. It produce a single value by performing computation on two values.

Example: (int a, int b) -> a * b

7. we can Compare two objects using lambda expression.

Example: (Pet  p1, Pet p2) -> p1.getAgeMonths().compareTo(p2.getAgeMonths())

6. Limitations of Java 8 lambda expression

Some of the limitations of java 8 lambda expression are,

* Lambda expressions can only access to the final variables of the enclosing scope.

* Code debugging is harder with lambda expressions.

“In this post we gone through few important topics on Java 8 lambda expression and we came to know that it’s a most popular feature of Java 8”

 

 

 

 

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *