Sobes.tech
Middle

Mis on lambdaavaldised Java-s ja milliseid võimalusi need pakuvad?

sobes.tech AI

Vastus AI-lt

Lambda expressions in Java are anonymous functions that allow writing code more concisely, especially when working with functional interfaces. They consist of a parameter block, the arrow ->, and the function body.

Main features:

  • Code reduction: Remove the need to create anonymous inner classes to implement functional interfaces.
  • Functional programming: Simplify the application of functional programming concepts, such as passing functions as arguments.
  • Improved readability: In some cases, make the code more understandable and easier to perceive.
  • Working with Stream API: They form the basis for efficient data stream processing in Java 8 and above.

Example:

// Traditional way with anonymous class
Runnable traditionalRunnable = new Runnable() {
    @Override
    public void run() {
        System.out.println("Hello from traditional runnable");
    }
};

// Using lambda expression
Runnable lambdaRunnable = () -> System.out.println("Hello from lambda runnable");

The lambda expression is bound to a functional interface — an interface with a single abstract method. The parameter types and return value of the lambda are determined by the signature of this abstract method.