Mark As Completed Discussion

Lambda Expressions

Lambda expressions are a powerful feature introduced in Java 8 that allow you to write concise and expressive code. They provide a way to represent anonymous functions and can be used in place of functional interfaces.

Syntax

A lambda expression consists of the following parts:

  • Parameter list: It represents the input parameters of the anonymous function.
  • Arrow token: It separates the parameter list from the body of the lambda expression.
  • Body: It represents the code that is executed when the lambda expression is invoked.

The general syntax of a lambda expression is:

SNIPPET
1(parameter-list) -> { body }

Here's an example:

TEXT/X-JAVA
1Runnable r = () -> {
2    System.out.println("Hello, World!");
3};

In this example, the lambda expression represents an anonymous function that takes no parameters and prints "Hello, World!" when invoked.

Usage

Lambda expressions are most commonly used with functional interfaces, which are interfaces that have a single abstract method. The lambda expression provides an implementation for this single method, allowing you to pass behavior as an argument to methods or assign it to variables.

Here's an example of using a lambda expression with the forEach method of the List interface:

TEXT/X-JAVA
1import java.util.ArrayList;
2import java.util.List;
3
4public class Main {
5
6    public static void main(String[] args) {
7        List<Integer> numbers = new ArrayList<>();
8        numbers.add(1);
9        numbers.add(2);
10        numbers.add(3);
11        numbers.add(4);
12        numbers.add(5);
13        
14        numbers.forEach(n -> System.out.println(n));
15    }
16
17}

In this example, we create a list of integers and use the forEach method to iterate over each element and print it. The lambda expression (n -> System.out.println(n)) represents the code that is executed for each element of the list.

Lambda expressions provide a concise and expressive way to represent behavior, making your code more readable and maintainable.

JAVA
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment