Nâng CaoJava iconJava

Stream API và lập trình hàm trong Java 8 là gì?

Stream API xử lý dữ liệu theo phong cách khai báo (declarative). Gồm ba phần: nguồn (collection, array), intermediate operations (filter, map, distinct, sorted — lazy), terminal operations (forEach, collect, reduce — kích hoạt xử lý). Functional interfaces (một abstract method): Function, Predicate, Consumer, Supplier. Lambda thay thế anonymous class.

Ví dụ: list.stream().filter(x -> x > 5).map(x -> x * 2).collect(toList()).

Lợi ích: code ngắn gọn, dễ parallel hóa với parallelStream(). Java 16+ bổ sung Stream.toList() thay cho .collect(Collectors.toList()) — ngắn gọn hơn và trả về unmodifiable list.

Xem toàn bộ Java cùng filter theo level & chủ đề con.

Mở danh sách Java