Sobes.tech
Junior

What are lambda expressions in Java?

sobes.tech AI

Answer from AI

A lambda expression in Java is a concise way to represent anonymous functions (functions without a name). They are used to create instances of functional interfaces.

Main components:

  • Parameter list: Enclosed in parentheses (). If there are no parameters, empty parentheses are used.
  • Arrow ->: Separates the parameter list from the body of the lambda expression.
  • Body: Can be a single expression or a block of code within curly braces {}.

Example without parameters:

// Functional interface
@FunctionalInterface
interface Greeting {
    void sayHello();
}

// Using a lambda expression
Greeting greeting = () -> System.out.println("Hello, World!");

Example with parameters:

// Functional interface
@FunctionalInterface
interface MathOperation {
    int operate(int a, int b);
}

// Using a lambda expression
MathOperation addition = (a, b) -> a + b;
MathOperation subtraction = (a, b) -> {
    return a - b;
};

Advantages:

  • Conciseness: Reduces boilerplate code.
  • Convenience: Useful with Stream API for collection processing.
  • Functional programming: Supports functional programming elements in Java.

Limitations:

  • Can only be used with functional interfaces (interfaces with a single abstract method).
  • Cannot have state (i.e., cannot modify variables outside their scope unless these variables are explicitly declared final or effectively final).

Lambda expressions were introduced in Java 8.