Java Lambda Expressions

Lambda expressions, introduced in Java 8, provide a clear and concise way to represent one method interface using an expression. They enable functional programming in Java and can simplify the development of Java applications.

1. Syntax

(parameters) -> expression
(parameters) -> { statements; }

2. Functional Interfaces

A functional interface is an interface with exactly one abstract method. Lambda expressions implement functional interfaces.

Example:

@FunctionalInterface
public interface Greeting {
    void sayHello(String name);
}

3. Using Lambda Expressions

Example: Implementing a Functional Interface

public class LambdaExample {
    public static void main(String[] args) {
        Greeting greeting = (name) -> System.out.println("Hello, " + name);
        greeting.sayHello("Alice"); // Outputs: Hello, Alice
    }
}

4. Lambda with Collections

Lambda expressions are often used with collections to simplify operations like sorting and iterating.

Example: Sorting a List

import java.util.ArrayList;
import java.util.List;

public class LambdaSortExample {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>();
        names.add("Bob");
        names.add("Alice");
        names.add("Charlie");

        names.sort((a, b) -> a.compareTo(b));
        names.forEach(name -> System.out.println(name));
        // Outputs: Alice, Bob, Charlie
    }
}

5. Method References

Method references are a shorthand notation of a lambda expression to call a method.

names.forEach(System.out::println);

6. Key Takeaways

  • Lambda expressions provide a concise way to implement functional interfaces.
  • Enable functional programming constructs in Java.
  • Simplify code for operations on collections and streams.
  • Understand the syntax and usage of lambda expressions and method references.
  • Functional interfaces are the basis for lambda expressions.