Category : Java | Sub Category : Java8 Features | By Prasad Bonam Last updated: 2023-11-13 04:12:43 Viewed : 237
The syntax of a lambda expression in Java consists of parameters, an arrow ->
, and a body. The basic syntax is as follows:
java(parameters) -> expression
or
java(parameters) -> { statements; }
Here are some basic examples to illustrate the syntax of lambda expressions:
java// Old way using an anonymous inner class
Runnable oldRunnable = new Runnable() {
@Override
public void run() {
System.out.println("Old way");
}
};
// Using lambda expression
Runnable newRunnable = () -> System.out.println("Lambda way");
java// Old way using an anonymous inner class
Comparator<Integer> oldComparator = new Comparator<Integer>() {
@Override
public int compare(Integer x, Integer y) {
return x.compareTo(y);
}
};
// Using lambda expression
Comparator<Integer> newComparator = (x, y) -> x.compareTo(y);
java// Old way using an anonymous inner class
MyInterface oldInterface = new MyInterface() {
@Override
public void myMethod(int x) {
for (int i = 0; i < x; i++) {
System.out.println("Old way");
}
}
};
// Using lambda expression
MyInterface newInterface = x -> {
for (int i = 0; i < x; i++) {
System.out.println("Lambda way");
}
};
java// Old way using an anonymous inner class
MathOperation oldOperation = new MathOperation() {
@Override
public int operate(int x, int y) {
return x + y;
}
};
// Using lambda expression
MathOperation newOperation = (x, y) -> {
int result = x + y;
System.out.println("Lambda way: " + result);
return result;
};
In these examples:
(parameters) -> expression
and (parameters) -> { statements; }
are used to create instances of functional interfaces.->
separates the parameter list from the body of the lambda expression.{}
. If the body contains multiple statements or is a block of statements, you use curly braces.Remember that lambda expressions are most commonly used with functional interfaces, which have only one abstract method. The lambda expression provides a concise way to implement that single method without explicitly creating an anonymous class.