Sobes.tech
Middle

What are lambda expressions in Java?

sobes.tech AI

Answer from AI

A lambda expression in Java is an anonymous function. It allows treating functionality as a method argument or as code as data.

Main characteristics:

  • Anonymity: It has no name.
  • Functional interface: A lambda expression is always associated with a functional interface (an interface with a single abstract method).
  • Syntax: (parameters) -> { body }

Example using the functional interface Consumer:

import java.util.function.Consumer;

// The functional interface Consumer<T> has one abstract method accept(T t)
Consumer<String> greeting = (name) -> {
    System.out.println("Hello, " + name);
};

greeting.accept("World"); // Output: Hello, World

Example using the interface Runnable:

// The interface Runnable has one abstract method run()
Runnable task = () -> {
    System.out.println("Task is running in a separate thread");
};

new Thread(task).start(); // Starts the task in a new thread

Syntax variations:

  • No parameters: () -> { System.out.println("Hello"); }
  • One parameter without parentheses: name -> System.out.println("Hello, " + name)
  • Multiple parameters with parentheses and types: (int a, int b) -> { return a + b; }
  • Multiple parameters without types (type inference): (a, b) -> a + b
  • Single-line body without return: (a, b) -> a + b
  • Multi-line body with curly braces and return (if needed): (a, b) -> { int sum = a + b; return sum; }

Lambda expressions make code more concise, readable, and enable functional programming in Java.