Module 23: Java 8 & Functional ProgrammingBeginner28 min read
Lambda Expressions, Functional Interfaces & Stream API
Write expressive, declarative pipelines with Java 8 Lambdas, Method References, Stream filter/map/reduce/collect, and null-safe Optional.
Key Takeaways & Core Concepts
- `Predicate<T>`:
T -> boolean(test(t)) — filtering conditions. - `Function<T, R>`:
T -> R(apply(t)) — transforming values. - `Consumer<T>`:
T -> void(accept(t)) — consuming items (e.g., logging). - `Supplier<T>`:
() -> T(get()) — lazy value generation.
Introduction
Java 8 transformed Java from a purely imperative OOP language into a hybrid OOP + Functional language by introducing Lambda Expressions, Functional Interfaces, Method References, the Stream API, and `Optional<T>`.
Stream Pipeline, Method References & Optional
1import java.util.*;
2import java.util.stream.Collectors;
3
4public class Main {
5 public static void main(String[] args) {
6 List<Integer> scores = List.of(45, 82, 91, 67, 91, 74);
7 List<Integer> topUnique = scores.stream()
8 .filter(s -> s >= 70)
9 .distinct()
10 .sorted(Comparator.reverseOrder())
11 .collect(Collectors.toList());
12
13 System.out.println("Top Unique Scores: " + topUnique);
14 Optional<Integer> max = scores.stream().max(Integer::compareTo);
15 System.out.println("Max Score: " + max.orElse(0));
16 }
17}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
17 lines
Note: Streams are non-mutating: `scores` remains unchanged while `topUnique` holds the filtered result.
Core Functional Interfaces (java.util.function)
- `Predicate<T>`:
T -> boolean(test(t)) — filtering conditions. - `Function<T, R>`:
T -> R(apply(t)) — transforming values. - `Consumer<T>`:
T -> void(accept(t)) — consuming items (e.g., logging). - `Supplier<T>`:
() -> T(get()) — lazy value generation.
(Variables captured by a Lambda from the enclosing scope must be `final` or effectively final.)
Stream API Architecture (Lazy vs Terminal)
A Stream is not a data structure—it is a declarative pipeline over a data source:
- 1Source:
collection.stream(),Arrays.stream(arr),Stream.of(...) - 2Intermediate Operations (Lazy):
filter,map,flatMap,sorted,distinct,limit,skip. Nothing executes until a terminal operation is invoked! - 3Terminal Operations (Eager):
collect,toList,reduce,count,findFirst,forEach.
map() vs flatMap() & Optional
map()transforms each element 1-to-1;flatMap()transforms 1-to-many and flattens nested streams (Stream<List<T>> -> Stream<T>).- `Optional<T>`: Models a potentially absent return value explicitly. Never call
opt.get()without checking—useorElse(),orElseGet(),orElseThrow(), ormap().
Common Mistakes
- Reusing a
Streamafter a terminal operation—streams are single-use and throwIllegalStateExceptionif reused. - Using
.parallelStream()blindly on small lists or blocking I/O—parallel streams share the commonForkJoinPooland only help on large CPU-bound workloads.
Practice & AssessmentJava Programming Tutorial
Test Your Understanding
Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.
Your Current Score
0 / 0 correct(0 attempted)