Chuyển đến nội dung chính
eLearner.app
Mô-đun 7 · Bài học 2 trong tổng số 214/14 trong khóa học~15 min
Bài học theo mô-đun (2/2)

API luồng

The Stream API in Java allows you to process collections of objects in a declarative way, leveraging functional programming. A Stream does not store data, but instead carries elements from a source (such as a list or an array) through a pipeline of operations.

A Stream pipeline consists of three parts:

  1. A source (e.g., list.stream())
  2. Zero or more intermediate operations (which return a new Stream, e.g., filter, map)
  3. A terminal operation (which produces a final result or side-effect and closes the Stream, e.g., collect, forEach, reduce)

Common Intermediate Operations

Intermediate operations are lazy: they are not executed until a terminal operation is invoked.

  • filter(Predicate): filters elements based on a boolean condition.
  • map(Function): transforms each element into another object by applying a function.
  • sorted(): sorts the elements of the Stream.
Code
List<String> names = Arrays.asList("Marco", "Anna", "Giovanni");
List<String> filtered = names.stream()
                             .filter(name -> name.startsWith("M"))
                             .map(name -> name.toUpperCase())
                             .collect(Collectors.toList()); // "MARCO"

Common Terminal Operations

  • forEach(Consumer): performs an action for each element of the Stream.
  • collect(Collector): gathers the Stream results into a container (e.g., a list using Collectors.toList()).
  • reduce(identity, BinaryOperator): combines the Stream elements into a single cumulative value.
Code
List<Integer> numbers = Arrays.asList(1, 2, 3, 4);
int sum = numbers.stream()
                 .reduce(0, (a, b) -> a + b); // Sums all numbers: 10

Try it yourself

tập thể dục#java.m7.l2.e1
Nỗ lực: 0Đang tải…

Complete the code using the stream of numbers to filter only even numbers, collect them into a new List named evens, and print it using System.out.println.

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

Start by calling `numbers.stream()`, append `.filter(n -> n % 2 == 0)`, and finally collect with `.collect(Collectors.toList())`.

Giải pháp khả dụng sau 3 lần thử

tập thể dục#java.m7.l2.e2
Nỗ lực: 0Đang tải…

Use streams to transform all names inside the names list to uppercase using map, and print them one by one using forEach with a method reference.

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

Use `.map(s -> s.toUpperCase())` followed by the terminal operation `.forEach(System.out::println)`.

Giải pháp khả dụng sau 3 lần thử

tập thể dục#java.m7.l2.e3
Nỗ lực: 0Đang tải…

Complete the code by calculating the sum of all numbers in the numbers list using a Stream and the reduce terminal operation with an initial value of 0. Print the sum.

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

Use `numbers.stream().reduce(0, (a, b) -> a + b)` and print the resulting variable.

Giải pháp khả dụng sau 3 lần thử