Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

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:

  1. Use lambda to simplify instances of functional interfaces.
  2. Write it in-line instead of creating anonymous class objects.
  3. 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.