Java Lambda Expressions
What are Lambda Expressions in Java?
Lambda Expressions, introduced in Java 8, provide a concise way to represent anonymous functions (functions without a name). They are primarily used to implement functional interfaces and enable a more functional programming style in Java.
A lambda expression allows you to write cleaner, shorter, and more readable code—especially when working with collections and streams.
Lambda Expression Syntax
The general syntax of a lambda expression is:
(parameter) -> expression
Variations:
- Single parameter (no parentheses required):
x -> x * x
- Multiple parameters:
(a, b) -> a + b
- Block of code (multiple statements):
(a, b) -> {
int result = a + b;
return result;
}
Using Lambda Expressions in Java
Lambda expressions are commonly used with methods that accept functional interfaces, such as forEach().
Example: Iterating a List with Lambda
import java.util.ArrayList;
public class LambdaIteration {
public static void main(String[] args) {
ArrayList<String> courses = new ArrayList<>();
courses.add("Java");
courses.add("Python");
courses.add("Data Science");
courses.forEach(course -> System.out.println(course));
}
}
Storing Lambda Expressions in Variables
A lambda expression can be assigned to a variable whose type is a functional interface (an interface with exactly one abstract method).
Example: Using Built-in Functional Interface
import java.util.ArrayList;
import java.util.function.Consumer;
public class LambdaVariableDemo {
public static void main(String[] args) {
ArrayList<Integer> marks = new ArrayList<>();
marks.add(75);
marks.add(85);
marks.add(95);
Consumer<Integer> printMark = m -> System.out.println("Mark: " + m);
marks.forEach(printMark);
}
}
Passing Lambda Expressions as Method Parameters
You can pass lambda expressions as arguments to methods. The method must accept a functional interface.
Example: Custom Functional Interface
interface TextFormatter {
String format(String input);
}
public class LambdaMethodParameter {
public static void main(String[] args) {
TextFormatter toUpper = str -> str.toUpperCase();
TextFormatter addPrefix = str -> ">> " + str;
applyFormat("lambda", toUpper);
applyFormat("lambda", addPrefix);
}
public static void applyFormat(String text, TextFormatter formatter) {
String result = formatter.format(text);
System.out.println(result);
}
}
Lambda vs Anonymous Class
Before Java 8, developers often used anonymous classes to implement interfaces. Lambda expressions provide a more concise alternative.
Example: Anonymous Class
interface Logger {
void log();
}
public class AnonymousExample {
public static void main(String[] args) {
Logger logger = new Logger() {
@Override
public void log() {
System.out.println("Logging using anonymous class");
}
};
logger.log();
}
}
Equivalent Lambda Expression
interface Logger {
void log();
}
public class LambdaExample {
public static void main(String[] args) {
Logger logger = () -> System.out.println("Logging using lambda");
logger.log();
}
}
Key Rules for Lambda Expressions
- Can only be used with functional interfaces
- Reduce boilerplate code significantly
- Improve readability for short operations
- Cannot replace classes with multiple methods
Advantages of Lambda Expressions
- Concise Syntax: Less code compared to traditional approaches
- Improved Readability: Easier to understand intent
- Functional Programming Support: Works seamlessly with streams
- Better Maintainability: Cleaner and more structured code