CodeBlanks Logo Icon CodeBlanks

forEach and count

Learn processing with forEach and counting with count.

The forEach terminal op

forEach(Consumer) is a terminal operation; it runs an action for each element and closes the stream. names.stream().forEach(s -> System.out.println(s)); prints each name.

forEach returns no value; it is used for side effects. On a sequential stream it walks elements in source order. Usually result collectors like Collectors.toList() are preferred over forEach; forEach is fine when a side effect is required.

count vs sum

count() returns the number of elements in the stream as long; sum() works only on numeric streams (IntStream etc.) and returns the total of values. Both are terminal.

For example names.stream().count() gives the name count; names.stream().mapToInt(String::length).sum() gives the total length. The reduce terminal can also produce a sum iteratively: .reduce(0, (a, b) -> a + b). All three suit different goals.

Practice Print and count with a stream

Declare List<String> names = new ArrayList<>();; add "Ayşe" and "Alex". First print each name with names.stream().forEach(s -> System.out.println(s));. Then print the count with System.out.println(names.stream().count());.

Starter code

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

public class Main {
    public static void main(String[] args) {
        // Declare List<String>, add two names, print with forEach, print count

    }
}

Sample solution

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

public class Main {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>();
        names.add("Ayşe");
        names.add("Alex");
        names.stream().forEach(s -> System.out.println(s));
        System.out.println(names.stream().count());
    }
}

Expected output

Ayşe
Alex
2

Questions and answers

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

1 Complete the count call

Question
long n = names.stream().filter(s -> s.length() > 3).____();
Answer
long n = names.stream().filter(s -> s.length() > 3).count();

Explanation: count() returns the number of elements.

2 What does count() return on a Stream?

  • int
  • void
  • long Correct answer
  • Optional<Long>

Explanation: count() returns a long; the number of elements in the stream.

3 Match the terminal operations

Term Meaning
forEach(...) Produces side effect
count() Element count
sum() Numeric total
reduce(...) Iterative reduction

All lessons in Intermediate