CodeBlanks Logo Icon CodeBlanks

Summary - Stream API basics

Combine filter, map and collect to write an employee filter.

Summary - Stream API basics

This group covered the core Stream API operations: stream() starts the stream, filter removes elements, map transforms, forEach and count are terminal ops, collect(Collectors.toList()) gathers the result into a List.

Intermediate operations are lazy; terminal operations are eager. A Stream is consumed once; reusing it is an error. The Predicate, Function and Consumer functional interfaces are given as lambdas.

Practice Stream chain: filter, map, collect

Declare List<String> names = new ArrayList<>();; add "Ayşe", "Alex", "Mehmet". Build the chain List<Integer> lengths = names.stream().filter(s -> s.length() > 3).map(s -> s.length()).collect(Collectors.toList());. Print the size with System.out.println(lengths.size());.

Starter code

Main.java
import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        // Declare List<String>, add 3 names; build filter+map+collect chain; print size

    }
}

Sample solution

Main.java
import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>();
        names.add("Ayşe");
        names.add("Alex");
        names.add("Mehmet");
        List<Integer> lengths = names.stream().filter(s -> s.length() > 3).map(s -> s.length()).collect(Collectors.toList());
        System.out.println(lengths.size());
    }
}

Expected output

3

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the operation types

Term Meaning
filter Filtering (intermediate)
map Transform (intermediate)
forEach Side effect (terminal)
count Counting (terminal)

2 Which one is a terminal operation?

  • collect Correct answer
  • map
  • filter
  • sorted

Explanation: collect is terminal; it gathers the stream into a List and closes it.

3 Match the Stream parts

Term Meaning
stream() Starts the stream
Collectors.toList() Gathers a List
Predicate<T> filter parameter
Function<T, R> map parameter

All lessons in Intermediate