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:
- A source (e.g.,
list.stream()) - Zero or more intermediate operations (which return a new Stream, e.g.,
filter,map) - 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.
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 usingCollectors.toList()).reduce(identity, BinaryOperator): combines the Stream elements into a single cumulative value.
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
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.
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
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.
Show hint
Use `.map(s -> s.toUpperCase())` followed by the terminal operation `.forEach(System.out::println)`.
Solution available after 3 attempts
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.
Show hint
Use `numbers.stream().reduce(0, (a, b) -> a + b)` and print the resulting variable.
Solution available after 3 attempts