Skip to content

How To Write Lambda Expressions

This lesson introduces the basic lambda expression structure with tips to write efficient code.

Gopi Gorantala
Gopi Gorantala
2 min read

Table of Contents

First, let us look at the basic structure of lambda expression. This could help us understand writing lambdas easily.

Basic Structure

The basic structure of lambda expression is:

Basic steps

Java Lambda expression contains the following parts:

Parameters-list: This can be empty or contain one or more parameters, separated by commas. If there is only one parameter, you can omit the parentheses.

  1. Lambda operator: This separates the parameter list from the lambda expression's body or, in simple terms, connects the argument list with the lambda expression's body.
  2. Expression: Finish with the expression or statement(s) to be executed: expression or { statements }.

Example

Here is an example of a lambda expression that takes two integers as input and returns their sum:

(int a, int b) -> a + b

This lambda expression takes two integer parameters a and b and returns their sum. Note that the parameter types are specified in parentheses, and the return type is inferred based on the expression.

() -> System.out.println("Hello, world!")

This lambda expression has an empty parameter list, and the body contains a single statement to print a message to the console.

Lambda expressions can be assigned to functional interfaces or used directly as arguments to methods. For example, to use the above lambda expression with the Runnable functional interface, you can write:

Runnable helloWorld = () -> System.out.println("Hello, world!");

This creates a Runnable object that executes the lambda expression when its run method is called.

Tips when writing lambda expressions

Parameter lists sometimes have zero or more parameters.

There are rules to follow when writing a lambda expression. We don’t need to follow all, but to improve code quality we have to follow these tips when writing a lambda expression.

  1. When there are no parameters, we should explicitly give ().

If there is a single parameter, we can ignore the parenthesis below. Both syntaxes are valid.

  • (message) -> {}
  • message -> {}
  • When the body is a single line, we can exclude the curly braces {, } and return. The following example explains it.
// Both of the below expressions are valid.

// 01: Lambda expression printing Hello on console
  () -> {
    System.out.println("Hello");
  }

// 02: Lambda expression printing Hello on console
  () -> System.out.println("Hello");
  • Java understands the underlined functional interface when running through the lambda expression. Because of this, we don’t need to have the parameter typed inside the parameters list.
// All of the below syntaxes print same output - Hello, fullName
(String fullName) -> {
    System.out.println("Hello, " + fullName);
}

// Above can be refactored as follows.
(fullName) -> {
    System.out.println("Hello, " + fullName);
}

// further more, we can replace it with
fullName -> System.out.println("Hello, " + fullName);
Java Streams APIJava

Gopi Gorantala Twitter

Gopi is an engineering leader with 12+ of experience in full-stack development—a specialist in Java technology stack. He worked for multiple startups, the European govt, and FAANG in India and Europe.

Comments


Related Posts

Members Public

Differences Between JDK, JRE, and JVM?

Short answer JDK, JRE, and JVM are essential components of the Java platform, each serving a distinct purpose. Here are the key differences between them: 1. JDK (Java Development Kit): The JDK is used by developers to write, compile, and debug Java code. 2. JRE (Java Runtime Environment): End-users use

Members Public

Difference Between String and char[] in Java

Short answer Strings String is an object with many helpful methods. String class in Java's standard library is designed to handle text as a sequence of characters. A string of characters (string object) is non-modifiable or immutable in Java. Once you've created it, you cannot modify

Members Public

What is an Object class in Java?

Short answer Object class is the super class of every class you can create. In Java, a class extends another class using the keyword extends. If you don't have any other class to extend, that's fine. The compiler will make your class extend the Object class.