Java — Lambda Expressions
Basic lambda
public class Main {
public static void main(String[] args) {
// Lambda expression
Runnable r = () -> System.out.println("Hello");
r.run();
// With parameters
MathOperation add = (a, b) -> a + b;
System.out.println(add.apply(3, 4));
}
@FunctionalInterface
interface MathOperation {
int apply(int a, int b);
}
}
Functional interfaces
@FunctionalInterface
interface Predicate<T> {
boolean test(T t);
}
@FunctionalInterface
interface Function<T, R> {
R apply(T t);
}
@FunctionalInterface
interface Consumer<T> {
void accept(T t);
}
Method references
import java.util.*;
List<String> names = List.of("Alice", "Bob", "Charlie");
// Static method reference
names.forEach(System.out::println);
// Instance method reference
String::toUpperCase
// Constructor reference
ArrayList::new
Lambda with collections
import java.util.*;
import java.util.stream.*;
List<Integer> nums = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
// Filter
List<Integer> evens = nums.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
// Map
List<Integer> doubled = nums.stream()
.map(n -> n * 2)
.collect(Collectors.toList());
// Reduce
int sum = nums.stream()
.reduce(0, Integer::sum);
Composing functions
Function<Integer, Integer> doubleIt = x -> x * 2;
Function<Integer, Integer> addTen = x -> x + 10;
Function<Integer, Integer> combined = doubleIt.andThen(addTen);
System.out.println(combined.apply(5)); // 20
Function<Integer, Integer> composed = addTen.compose(doubleIt);
System.out.println(composed.apply(5)); // 20
Mini Practice
Write Java code that:
- Creates a lambda and passes it to a function
- Uses method references
- Chains stream operations with lambdas
Up Next
In the next lesson, you'll learn about Streams — the Stream API.
Related Topics
Frequently Asked Questions about Lambda Expressions
What is Lambda Expressions in Java?
Lambda Expressions is a fundamental concept in Java. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Lambda Expressions?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Lambda Expressions.
Why is Lambda Expressions important in Java?
Lambda Expressions is essential for Java development. Understanding this concept will help you write better code and solve real-world problems more effectively.