DEV Community

Cover image for Java 8 - Lambda Expression 101
Sangharsha Chaulagain
Sangharsha Chaulagain

Posted on

Java 8 - Lambda Expression 101

One of the biggest changes in Java 8 was lambda expression. The main reason to bring lambda expression to Java is to bring the benefit of functional programming into Java.

What is Lambda Expression?

It is a concise representation of anonymous functions that can be passed around. Unlike methods, it is nameless and is not associated with the particular class. It can be passed as an argument to a method or stored in a variable. Lambda expression is said to be a concise representation since there is no need to write boilerplate code as we do for anonymous classes.

Convert method into Lambda Expression

It is really very easy to convert a method into a lambda expression. Following are some rules:

  • Remove the name
  • Remove the return type
  • Remove the modifier
  • Add the arrow symbol(->)

Example 1:

Let’s take the following method,

public void sayHello() {
    System.out.println(Hello);
}
Enter fullscreen mode Exit fullscreen mode

After removing the name, the return type and the modifier from the above method,

() {
    System.out.println(Hello);
}
Enter fullscreen mode Exit fullscreen mode

But to make it a valid lambda expression, we need to add a special symbol,
->. Hence the above method becomes:

() -> { System.out.println(Hello); }
Enter fullscreen mode Exit fullscreen mode

The above is the valid lambda expression. But we can concise the above lambda expression even more. If we have only one statement in the body of lambda expression, curly brackets are optional.

() -> System.out.println(Hello);
Enter fullscreen mode Exit fullscreen mode

Note: If multiple statements are in the body of the lambda expression then the curly bracket is mandatory.


Top comments (0)