Topic 14 of 30 · Advanced
Lambdas & Stream API
Functional style: map, filter, reduce and collectors.
Concept
A lambda is a short anonymous function implementing a functional interface: (a, b) -> a + b. Method references (String::length) are even shorter.
Streams process collections declaratively. Intermediate operations (filter, map, sorted) are lazy; a terminal operation (collect, count, reduce) triggers execution.
Collectors.groupingBy, joining and toMap cover most reporting tasks. Streams can't be reused once consumed.
Code (Java 21)
record Emp(String name, String dept, double salary) {}
List<Emp> emps = List.of(
new Emp("Asha", "IT", 90), new Emp("Ravi", "IT", 70), new Emp("Meena", "HR", 60));
Map<String, Double> avgByDept = emps.stream()
.collect(Collectors.groupingBy(Emp::dept, Collectors.averagingDouble(Emp::salary)));
List<String> top = emps.stream()
.filter(e -> e.salary() > 65)
.sorted(Comparator.comparingDouble(Emp::salary).reversed())
.map(Emp::name)
.toList();
int sumSquares = IntStream.rangeClosed(1, 5).map(x -> x * x).sum(); // 55Remember
- Intermediate ops are lazy.
- map = one-to-one, flatMap = one-to-many.
- Avoid side effects inside stream operations.
Interview questions
map vs flatMap?
map transforms each element into one result. flatMap transforms each into a stream and flattens them into one stream.
Find the second-highest salary with streams.
emps.stream().map(Emp::salary).distinct().sorted(Comparator.reverseOrder()).skip(1).findFirst()
Lesson test
Take an 8-question test on “Lambdas & Stream API” — concepts, output prediction, bug spotting and interview questions.