Java Lambda Expressions

Lambda expressions were introduced in Java 8 to make functional-style programming easier. They allow you to represent a function as a concise block of code and are commonly used with collections, streams, and functional interfaces.

Lambda Syntax

A lambda consists of parameters, the arrow operator, and the function body.

Java
Basic lambda expression.
Runnable task = () -> System.out.println("Hello Java");

task.run();
Java
Lambda with parameters.
(a, b) -> a + b

Functional Interfaces

A functional interface contains exactly one abstract method. Lambda expressions can be assigned to functional interface types.

Java
Creating and using a custom functional interface.
@FunctionalInterface
interface Calculator {
    int calculate(int a, int b);
}

public class Main {
    public static void main(String[] args) {
        Calculator add = (a, b) -> a + b;

        System.out.println(add.calculate(10, 20));
    }
}

Built-in Functional Interfaces

Java provides common functional interfaces in java.util.function, including Predicate, Consumer, Function, and Supplier.

Java
Examples of common functional interfaces.
Predicate<Integer> positive = n -> n > 0;
Consumer<String> printer = text -> System.out.println(text);
Function<String, Integer> length = text -> text.length();
Supplier<String> message = () -> "Hello Java";

Lambdas with Collections

Lambda expressions are frequently used to process collections with methods such as forEach and removeIf.

Java
Using lambda expressions with a list.
import java.util.ArrayList;
import java.util.List;

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

        names.forEach(name -> System.out.println(name));

        names.removeIf(name -> name.startsWith("B"));

        System.out.println(names);
    }
}

Method References

A method reference provides a shorter syntax when an existing method already performs the required operation.

Java
Replacing a lambda with a method reference.
List<String> names = List.of("Alice", "Bob", "Charlie");

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

Lambda Best Practices

Keep lambda expressions short and readable. Use method references when they make the code clearer. Avoid putting large amounts of business logic inside a lambda.

Use meaningful parameter names when a lambda contains more than a simple expression, and prefer standard functional interfaces when they accurately represent the operation.

Conclusion

Lambda expressions make Java code shorter and more expressive, especially when working with functional interfaces, collections, and streams. Understanding lambda syntax and common functional interfaces is an important step toward modern Java development.