collect() trong Stream API thu thập element từ stream vào collection. Chỉ định loại collection qua Collectors (Enum/factory). Thường dùng: Collectors.toList(), .toSet(), .toMap().
Cú pháp
<R, A> R collect(Collector<? super T, A, R> collector)
Ví dụ: takeWhile, dropWhile, iterate + collect
import java.util.*;
import java.util.stream.*;
public class StreamCollectMethodTest {
public static void main(String args[]) {
List<String> list = List.of("a", "b", "c", "d", "e", "f", "g", "h", "i");
// takeWhile: lấy cho đến khi điều kiện false (Java 9+)
List<String> subset1 = list.stream()
.takeWhile(s -> !s.equals("e"))
.collect(Collectors.toList());
System.out.println(subset1); // [a, b, c, d]
// dropWhile: bỏ qua cho đến khi điều kiện false (Java 9+)
List<String> subset2 = list.stream()
.dropWhile(s -> !s.equals("e"))
.collect(Collectors.toList());
System.out.println(subset2); // [e, f, g, h, i]
// iterate với predicate (Java 9+): start, hasNext, next
List<Integer> numbers = Stream.iterate(1, i -> i <= 10, i -> i+1)
.collect(Collectors.toList());
System.out.println(numbers); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
}
}
Kết quả
[a, b, c, d] [e, f, g, h, i] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Các Collector thường dùng
| Collector | Trả về | Mô tả |
|---|---|---|
toList() | List<T> | ArrayList (mutable) |
toSet() | Set<T> | HashSet (unique) |
toMap(keyMapper, valMapper) | Map<K,V> | HashMap |
toCollection(Supplier<C>) | C | Collection tùy chỉnh (LinkedList, TreeSet...) |
joining() | String | Nối element (CharSequence) |
groupingBy(classifier) | Map<K, List<T>> | Group by key |
partitioningBy(predicate) | Map<Boolean, List<T>> | Chia 2 group true/false |
collectingAndThen(downstream, finisher) | R | Post-process kết quả collector |
Java 9 mới: Collector bổ sung
Collectors.filtering(predicate, downstream): Lọc trong group.Collectors.flatMapping(mapper, downstream): FlatMap trong group.Stream.iterate(seed, hasNext, next): Iterate có điều kiện dừng.takeWhile/dropWhile: Prefix take/drop dựa trên predicate.
collect() là terminal operation mạnh nhất Stream API – biến stream thành data structure concrete.