Skip to main content
eLearner.app
Module 7 · Lesson 2 of 214/14 in the course~15 min
Module lessons (2/2)

Stream 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

Exercise#java.m7.l2.e1
Attempts: 0Loading…

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.

Loading editor…
Show hint

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

Solution available after 3 attempts

Exercise#java.m7.l2.e2
Attempts: 0Loading…

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.

Loading editor…
Show hint

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

Solution available after 3 attempts

Exercise#java.m7.l2.e3
Attempts: 0Loading…

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.

Loading editor…
Show hint

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

Solution available after 3 attempts