Sobes.tech
Junior

What does lambda expressions in Java allow you to do?

sobes.tech AI

Answer from AI

Lambda expressions in Java, introduced in Java 8, allow:

  • Implementing interfaces with a single abstract method (functional interfaces): This is their main purpose. Lambdas provide a concise syntax for creating instances of functional interfaces.
// Before Java 8
Runnable runnable = new Runnable() {
    @Override
    public void run() {
        System.out.println("Hello pre-Java 8!");
    }
};

// With Java 8
Runnable lambdaRunnable = () -> System.out.println("Hello Java 8!");
  • Passing behavior (functions) as arguments to methods: This extends the capabilities of functional programming in Java. Methods can accept lambda expressions as parameters.
// Example of using Stream API with a lambda
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
names.stream()
     .filter(name -> name.startsWith("A")) // Lambda as argument to filter
     .forEach(System.out::println);       // Lambda (Method Reference) as argument to forEach
  • Using Stream API: Lambda expressions are fundamental for working with the new Stream API, enabling efficient processing of data collections.
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sumOfEven = numbers.stream()
                      .filter(n -> n % 2 == 0)
                      .mapToInt(Integer::intValue)
                      .sum();
  • Simplifying implementation of anonymous inner classes for functional interfaces: Lambdas replace verbose syntax of anonymous classes in this context.

  • Improving code readability: For simple operations, lambdas make the code more concise and understandable.

  • Allowing deferred execution of code: A lambda expression describes an action that will be executed later when invoked.

Lambdas also have access to local variables of the outer scope (if they are effectively final).

Overall, lambda expressions make Java more expressive and suitable for functional programming styles.