Middle
What are lambda expressions in Java and what capabilities do they provide?
sobes.tech AI
Answer from AI
A lambda expression in Java is an anonymous function that does not belong to any class and can be passed as an object.
Syntax: (parameters) -> { body }
Capabilities:
- Functional Interface: A lambda expression can be assigned to a variable of a functional interface type (an interface with a single abstract method).
// Functional interface @FunctionalInterface interface MyInterface { void myMethod(); } // Using lambda expression MyInterface lambda = () -> System.out.println("Hello from lambda!"); lambda.myMethod(); - Simplification of code writing: Replaces anonymous inner classes for implementing functional interfaces.
// Before Java 8 (anonymous class) Thread thread1 = new Thread(new Runnable() { @Override public void run() { System.out.println("Old way"); } }); // From Java 8 (lambda) Thread thread2 = new Thread(() -> System.out.println("Lambda way")); - Using in Stream API: Integrated with Stream API for performing operations on collections.
List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); names.stream() .filter(name -> name.startsWith("A")) // Lambda expression .forEach(System.out::println); // Method reference lambda - Deferred execution: Code inside the lambda expression executes only when the functional method is called.
- Scope of variables: Lambda expressions can capture variables from the outer scope (local variables must be final or effectively final).
| Advantage | Description |
|---|---|
| Conciseness of code | Reduces "verbosity" compared to anonymous classes. |
| Improved readability | Code becomes more concise and understandable. |
| Parallel processing | Supported by Stream API for parallel operations. |