Lambda Expressions

Lambda expressions in Java provide a clear and concise way to represent one method interface using an expression. This tutorial will teach you how to use lambda expressions.

Syntax of Lambda Expressions

The syntax of a lambda expression is as follows:


(parameters) -> expression
// or
(parameters) -> { statements; }
      

Using Lambda Expressions

Lambda expressions are primarily used to define the inline implementation of a functional interface:


@FunctionalInterface
interface MyFunctionalInterface {
    void display();
}

public class Main {
    public static void main(String[] args) {
        MyFunctionalInterface msg = () -> {
            System.out.println("Hello, this is a lambda expression.");
        };
        msg.display();
    }
}
      

Lambda Expressions and Collections

Lambda expressions can be used with collections to perform various operations like filtering and iterating:


import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List names = Arrays.asList("Alice", "Bob", "Charlie");
        names.forEach(name -> System.out.println(name));
    }
}
      

In this example, a lambda expression is used to print each name in the list.

Continue exploring our intermediate tutorials to learn more about Java programming.

 

Scroll to Top