Syntax and basic examples

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:

Example 1: Single Parameter and Expression

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");

Example 2: Multiple Parameters and Expression

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);

Example 3: Single Parameter and Block of Statements

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"); } };

Example 4: Multiple Parameters and Block of Statements

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:

  • The lambda expressions (parameters) -> expression and (parameters) -> { statements; } are used to create instances of functional interfaces.
  • The arrow -> separates the parameter list from the body of the lambda expression.
  • If there is only one parameter and the body is a single expression, you can omit the curly braces {}. 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.

Search
Related Articles

Leave a Comment: