Java 8 Lambda Expressions

Lambda expressions are a new feature introduced in Java 8. In this post we will provide an overview of what is Lambda expressions and how to use them.

Lambda Expressions

What is a lambda expression

A lambda expression is a way to expression a functional interface or an Interface with only one abstract method such as Runnable / Callable in a more concise manner.

How do I use a lambda expression

Lets look at an example with and without lambda expression. To implement the callable interface in Java 7 you would need to do the following.

Now using Java 8 and lambda expressions we can represent this a lot cleaner and simpler.

So what has happened ?

  • The ()open / close brackets represents the input to the function. In this case the call() method has no arguments hence we pass no arguments
  • The -> is an arrow token
  • And 20 is the lambda body. If the body uses more than one line then you will need to use open/close curly braces. The lambda body is the code you wish to execute, in this case the code inside the call() method.

More Examples:

Below I have provided a few common examples.

Lambda Expression with zero arguments:

Functional Interface:

Lambda expression:

Lambda Expression with one arguments:

Functional Interface:

Lambda expression:

Lambda Expression with multiple arguments:

Functional Interface:

Lambda expression:

You can if you wish, define the type information

Lambda Expression code block:

I hope this post has provided some insight on how lambda expressions are used in Java 8.

Similar posts

  1. Java 8 Functional Interface
  2. Java 8 stream allMatch, noneMatch and anyMatch Examples
  3. CountDownLatch in Java
  4. Read a CSV file in Java

References

  1. Java 8 Lambda Expression Tutorial

 

Leave a Reply