メインコンテンツにスキップ
eLearner.app
モジュール 7 · レッスン 2 / 2コース内の 14/14~15 min
モジュールのレッスン (2/2)

ストリームAPI

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

運動#java.m7.l2.e1
試行回数: 0読み込み中…

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.

エディターを読み込み中…
ヒントを表示

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

3 回の試行後に解決策が利用可能になります

運動#java.m7.l2.e2
試行回数: 0読み込み中…

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.

エディターを読み込み中…
ヒントを表示

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

3 回の試行後に解決策が利用可能になります

運動#java.m7.l2.e3
試行回数: 0読み込み中…

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.

エディターを読み込み中…
ヒントを表示

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

3 回の試行後に解決策が利用可能になります