Java 8 FAQ: Top Questions
2. What is a lambda expression in Java 8 and how is it used?
Lambda expressions were introduced in Java 8 to support functional programming. They provide a concise way to represent an anonymous function that can be passed around and executed.
π Syntax:
(parameters) -> expression
(parameters) -> { statements }
πΊοΈ Step-by-Step Instructions:
- Use lambda to simplify instances of functional interfaces.
- Write it in-line instead of creating anonymous class objects.
- Lambda can be assigned to any variable or passed as method arguments.
π₯ Example Input:
List names = Arrays.asList("Alice", "Bob", "Charlie");
names.forEach(name -> System.out.println(name));
π Expected Output:
Alice
Bob
Charlie
β Java 8 Solution:
import java.util.Arrays;
import java.util.List;
public class LambdaExample {
public static void main(String[] args) {
List names = Arrays.asList("Alice", "Bob", "Charlie");
names.forEach(name -> System.out.println(name));
}
}
π Detailed Explanation:
- Lambda = Anonymous Function: It allows writing methods inline without needing a full class implementation.
- Used with Functional Interfaces: Such as
Runnable
,Comparator
,Predicate
. - Cleaner Syntax: No need to write boilerplate code like method declarations.
π οΈ Use Cases:
- Simplifying event listeners and callbacks.
- Using lambdas in Streams for filters, maps, and iterations.
- Reducing code verbosity in single-method implementations.