Lambda Expressions
Overview
Introduced in Java 8, Lambda Expressions are a way to write anonymous methods (functions without names) concisely. Before Java 8, if you wanted to pass a simple piece of behavior into a method (like a click listener or a sorting rule), you had to write a clunky 'Anonymous Inner Class'. Lambdas allow you to treat code as data. This paradigm shift brought functional programming capabilities to Java, making code massively more readable, reducing boilerplate, and serving as the foundation for the Streams API.
Syntax
The arrow `->` separates the input parameters from the execution body. If there's only one parameter, you can drop the `()`. If there's only one line of execution, you can drop the `{}` and the `return` keyword.
// Syntax: (parameters) -> { body }
// 1. No parameters
() -> System.out.println("No args lambda");
// 2. Single parameter (parentheses are optional)
name -> System.out.println("Hello " + name);
// 3. Multiple parameters
(a, b) -> a + b; // implicitly returns the sum
// 4. Multi-line body
(x, y) -> {
int sum = x + y;
System.out.println("Sum: " + sum);
return sum;
};Lambdas can only be used to implement 'Functional Interfaces'—which are interfaces that contain exactly one abstract method (like Runnable, Comparator, or Callable).
List<String> names = Arrays.asList("John", "Alice", "Bob");
// BEFORE JAVA 8 (Anonymous Inner Class)
Collections.sort(names, new Comparator<String>() {
@Override
public int compare(String a, String b) {
return a.compareTo(b);
}
});
// AFTER JAVA 8 (Lambda)
Collections.sort(names, (a, b) -> a.compareTo(b));
// EVEN BETTER (Method Reference)
Collections.sort(names, String::compareTo);Common Pitfalls
- Trying to mutate local variables from outside the lambda scope. Java enforces that variables used inside lambdas are 'effectively final'.
- Overusing lambdas for extremely complex logic. If a lambda spans 20 lines, it should be extracted into a regular method for readability.
Interview Tips
- Lambdas enable functional programming in Java, drastically reducing boilerplate code for anonymous inner classes.
Real-World Example
Lambdas are used extensively when querying databases asynchronously or configuring security rules in Spring Boot.
public class SecurityConfig {
// Spring Security configuration using lambdas
public void configureSecurity(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/public/**").permitAll()
.requestMatchers("/api/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
)
.formLogin(form -> form.loginPage("/login").permitAll());
}
}