
Introduction
A Lambda Expression in Java is a short way to write an implementation of a functional interface.
Lambda expressions were introduced in Java 8.
They are mainly used with functional interfaces and collections.
1. Lambda Syntax
(parameters) -> expression
or
(parameters) -> {
// statements
}
2. Simple Lambda Example
interface Message {
void show();
}
public class Main {
public static void main(String[] args) {
Message message = () -> System.out.println("Hello Java");
message.show();
}
}
Output:
Hello Java
3. Lambda with Parameters
interface Addition {
int add(int a, int b);
}
public class Main {
public static void main(String[] args) {
Addition addition = (a, b) -> a + b;
System.out.println(addition.add(10, 20));
}
}
Output:
30
4. Lambda with Multiple Statements
interface Calculator {
int calculate(int a, int b);
}
public class Main {
public static void main(String[] args) {
Calculator calculator = (a, b) -> {
int result = a * b;
return result;
};
System.out.println(calculator.calculate(5, 4));
}
}
Output:
20
5. Lambda with Runnable
public class Main {
public static void main(String[] args) {
Runnable task = () -> {
System.out.println("Task is running");
};
Thread thread = new Thread(task);
thread.start();
}
}
Output:
Task is running
6. Lambda with forEach()
Lambda expressions are commonly used with collections.
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> names = Arrays.asList("Java", "Spring", "React");
names.forEach(name -> System.out.println(name));
}
}
Output:
Java
Spring
React
7. Functional Interface
A Functional Interface is an interface that contains exactly one abstract method.
Example:
@FunctionalInterface
interface Greeting {
void sayHello();
}
Common built-in functional interfaces:
| Interface | Purpose |
|---|---|
Predicate<T> |
Returns true or false |
Function<T, R> |
Converts one value into another |
Consumer<T> |
Performs an action |
Supplier<T> |
Supplies a value |
8. Lambda with Predicate
import java.util.function.Predicate;
public class Main {
public static void main(String[] args) {
Predicate<Integer> isEven = number -> number % 2 == 0;
System.out.println(isEven.test(10));
}
}
Output:
true
9. Lambda with Function
import java.util.function.Function;
public class Main {
public static void main(String[] args) {
Function<String, Integer> length = text -> text.length();
System.out.println(length.apply("Java"));
}
}
Output:
4
10. Lambda with Consumer
import java.util.function.Consumer;
public class Main {
public static void main(String[] args) {
Consumer<String> print = text -> System.out.println(text);
print.accept("Hello Lambda");
}
}
Output:
Hello Lambda
Conclusion
Lambda Expressions make Java code shorter and easier to read.
They are commonly used with:
Functional Interfaces
Collections
forEach()Streams
Threads
PredicateFunctionConsumerSupplier
Lambda expressions are an important feature introduced in Java 8.



