Sobes.tech
Junior

What are lambda expressions in Java?

sobes.tech AI

Answer from AI

A lambda expression in Java is an anonymous function that allows you to pass blocks of code as objects. It provides a concise way to implement functional interfaces (interfaces with a single abstract method).

Syntax of a lambda expression:

  • List of parameters (can be empty).
  • The -> operator.
  • Expression body (can be an expression or a block of statements).

Examples:

// Lambda for the functional interface Runnable
Runnable task = () -> System.out.println("Hello from lambda!");

// Lambda for the functional interface Comparator<Integer>
Comparator<Integer> comparator = (a, b) -> a.compareTo(b);

// Lambda with a block of statements
Consumer<String> greeter = name -> {
    String message = "Hello, " + name + "!";
    System.out.println(message);
};

Key features:

  • Anonymity: they have no name.
  • Functional interfaces: used to implement functional interfaces.
  • Conciseness: allow writing more compact code compared to anonymous classes.
  • Variable capture: can capture effectively final local variables from the surrounding context.

Using lambda expressions improves code readability and simplifies working with APIs oriented towards functional programming, such as the Stream API.

What are lambda expressions in Java? — QA / QA… - sobes.tech