Skip to content

Java 8 Lambda Expression#

Definition#

  • A lambda expression is a short block of code which takes in parameters and returns a value. Lambda expressions are similar to methods, but they do not need a name and they can be implemented right in the body of a method.

  • Java 8 introduced an arrow(function pointer) ->. This is used in Lambda methods with the main purpose is separating a Lambda method into 2 parts: parameters and body method/function(Lambda function body).

1
(int a, int b) -> {do something};
  • Lambda expression can be defined as an anonymous function because it has enough characteristics of a function: parameters and body. The parameters of a function may or may not be required and the body may have or have not the return value.
  • Base on the input parameters, the lambda expression will process codes in body to return the result.
  • Lambda expression provides an implementation way for method defined in Java 8 Functional Interface. In addition, lambda expression is used in libraries of Collection as filter, map, findAny...
  • Lambda expression helps us to reduce the number of codes and support sequential and parallel streams effectively in Stream API.

Example#

Hello.java
1
2
3
4
5
6
@FunctionalInterface
public interface Hello {

    public String sayHello(String name);

}
LambdaExpression.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public class LambdaExpression {

    public static void main(String[] args) {

        Hello hello = (name) -> "Hello " + name;

        System.out.println(hello.sayHello("Lambda"));

    }

}
//the result in the terminal


Hello Lambda

See Also#