Sobes.tech
Junior

What are lambda expressions in Java?

sobes.tech AI

Answer from AI

A lambda expression in Java is an anonymous (nameless) function that implements a functional interface.

Main characteristics:

  • They have no name.
  • They can have parameters.
  • The body can consist of a single expression or a block of statements.
  • The return type is not specified (it is inferred automatically).
  • They are necessary for functional programming and working with streams (Streams API).

Syntax:

// Without parameters
() -> { // body }

// With one parameter (type can be omitted)
param -> expression

// With multiple parameters (type can be omitted, parentheses are needed)
(param1, param2) -> { // body }

Example of usage:

// Functional interface (built-in)
import java.util.function.Consumer;

// Implementation using a lambda
Consumer<String> printer = s -> System.out.println(s);
printer.accept("Hello world!");

// Using in a method that accepts a functional interface
import java.util.Arrays;
import java.util.List;

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
numbers.forEach(n -> System.out.println(n)); // forEach accepts a Consumer

Advantages:

  • More concise code.
  • Improved readability (in simple cases).
  • Ability to use functional programming.
  • Simplifies working with collections and multithreading.

Limitations:

  • Nested or long lambdas can be difficult to understand.
  • They have no state (cannot have instance fields).