Task 3 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

11.4 Lambdas and streams — filtering and counting

Lesson

Describing a computation over a list

A stream lets you process a collection by describing what to do rather than writing loops. Call .stream() on a list, then chain operations. filter(condition) keeps only the elements that pass — the condition is a lambda — and count() reports how many remain. forEach(action) runs an action on each element in order.


Worked example

List<Integer> nums = List.of(3, -1, 4, -2, 5);
long positives = nums.stream()
    .filter(n -> n > 0)
    .count();
System.out.println(positives);   // 3

nums.stream().filter(n -> n > 0).forEach(n -> System.out.println(n));
// 3, then 4, then 5 — in list order

count() returns a long; cast to int if you need one.


▶ Try it: run this — count the positives, then print them in order.



filter(n -> n > 0) keeps...


count() on a stream returns...


Type exactly what this program prints.

import java.util.List;
public class Main { public static void main(String[] a){
    List<Integer> xs = List.of(1, 2, 3, 4, 5, 6);
    long c = xs.stream().filter(n -> n % 2 == 0).count();
    System.out.println(c);
}}

The condition passed to filter is...


True or false?