Stream API (Java 8) xử lý dữ liệu theo phong cách khai báo — mô tả "muốn gì" thay vì "làm thế nào". Stream KHÔNG phải data structure, mà là pipeline đi qua source.
Ba phần của pipeline:
1. Source: collection.stream(), Arrays.stream(arr), Files.lines(path).
2. Intermediate (lazy): filter, map, flatMap, distinct, sorted. Chỉ chạy khi gặp terminal.
3. Terminal (eager): forEach, collect, reduce, count, toList (Java 16+).
List<String> names = users.stream()
.filter(u -> u.getAge() >= 18)
.map(User::getName)
.sorted()
.toList(); // Java 16+: ngắn hơn collect(toList())Functional interfaces (1 abstract method) là "ngôn ngữ" của Stream — lambda implement chúng: Function<T,R>, Predicate<T>, Consumer<T>, Supplier<T>.
Lưu ý:
- Stream dùng một lần — sau terminal, dùng lại throw IllegalStateException.
- parallelStream() chỉ thực sự nhanh với dataset lớn (>10K), op stateless. Đừng dùng cho I/O.
- Không side effect trong intermediate op (peek chỉ debug).
- toList() (Java 16+) trả unmodifiable list, khác collect(Collectors.toList()) mutable.
The Stream API (Java 8) processes data declaratively — describe "what you want" instead of "how to do it". A Stream is NOT a data structure; it is a pipeline over a source.
Three parts:
1. Source: collection.stream(), Arrays.stream(arr), Files.lines(path).
2. Intermediate (lazy): filter, map, flatMap, distinct, sorted. Nothing runs until a terminal op appears.
3. Terminal (eager): forEach, collect, reduce, count, toList (Java 16+).
List<String> names = users.stream()
.filter(u -> u.getAge() >= 18)
.map(User::getName)
.sorted()
.toList(); // Java 16+: shorter than collect(toList())Functional interfaces (single abstract method) are the "language" of Streams — lambdas implement them: Function<T,R>, Predicate<T>, Consumer<T>, Supplier<T>.
Caveats:
- A Stream is single-use — reusing after a terminal throws IllegalStateException.
- parallelStream() is only really faster for large (>10K), stateless workloads. Do not use for I/O.
- No side effects in intermediate ops (peek is debug-only).
- toList() (Java 16+) returns an unmodifiable list, unlike the mutable collect(Collectors.toList()).