Lambda Expressions in Java
Lambda expressions, introduced in Java 8, allow you to write anonymous functions in a compact syntax. They are the foundation of functional programming sup...
Concise Code with Lambda Expressions
Lambda expressions, introduced in Java 8, allow you to write anonymous functions in a compact syntax. They are the foundation of functional programming support in Java and work directly with functional interfaces, which are interfaces that declare exactly one abstract method. Lambdas make code more concise by removing the boilerplate of anonymous inner classes.
The syntax of a lambda is: (parameters) -> expression or (parameters) -> { statements; }. If there is a single parameter, parentheses are optional. If the body is a single expression, braces and the return keyword are optional.
Before Java 8, sorting a list required an anonymous class:
Collections.sort(names, new Comparator<String>() { public int compare(String a, String b) { return a.compareTo(b); } });
With a lambda, this becomes:
Collections.sort(names, (a, b) -> a.compareTo(b)); // Or even simpler with method reference: names.sort(String::compareTo);
Lambdas can capture variables from their enclosing scope, but only effectively final variables, meaning variables whose value does not change after initialization. This restriction ensures that captured variables behave predictably in concurrent contexts.
Lambdas are not just syntactic sugar; they enable a new programming paradigm in Java. Combined with the Stream API, they allow expressive data processing pipelines. Combined with functional interfaces like Predicate, Function, Supplier, and Consumer in java.util.function, they make code modular and reusable.
A Runnable lambda is a clean way to define a background task:
Thread t = new Thread(() -> System.out.println("Running in background")); t.start();
Interview tip: A popular interview question asks whether lambdas create a new class at runtime like anonymous inner classes do. The answer is no. Lambdas are implemented using invokedynamic bytecode instruction, which is more efficient and does not generate a separate class file for each lambda at compile time.