Sub topic 6
Getting Results: forEach, count, anyMatch, and findFirst
A stream pipeline does no work until it ends with a terminal operation. A terminal operation is the last step in a pipeline. It runs the pipeline and gives you a result or an action. This chapter covers the terminal operations you will use most often.
What a Terminal Operation Does
Intermediate operations like filter and map only describe the work. The terminal operation starts it. After a terminal operation runs, the stream is used up, and you cannot use it again.
The Common Terminal Operations
| Operation | What it returns | Use it to |
|---|---|---|
| `forEach` | nothing (`void`) | do something with each element |
| `count` | `long` | count the elements |
| `anyMatch` | `boolean` | check if at least one element matches |
| `allMatch` | `boolean` | check if every element matches |
| `noneMatch` | `boolean` | check if no element matches |
| `findFirst` | `Optional` | get the first element, if there is one |
A predicate is a function that takes an element and returns true or false. The three match methods each take a predicate.
A Worked Example
import java.util.List;
public class TerminalOpsExample {
public static void main(String[] args) {
List<String> fruits = List.of("apple", "banana", "cherry", "avocado");
// forEach: do something with each element
fruits.stream().forEach(f -> System.out.println(f));
// count: how many fruits start with "a"?
long aCount = fruits.stream()
.filter(f -> f.startsWith("a"))
.count();
System.out.println(aCount); // 2
// anyMatch, allMatch, noneMatch
System.out.println(fruits.stream().anyMatch(f -> f.length() > 6)); // true
System.out.println(fruits.stream().allMatch(f -> f.length() > 3)); // true
System.out.println(fruits.stream().noneMatch(String::isEmpty)); // true
// findFirst: the first fruit that starts with "c"
String firstC = fruits.stream()
.filter(f -> f.startsWith("c"))
.findFirst()
.orElse("none");
System.out.println(firstC); // cherry
}
}Each line makes a new stream with fruits.stream(). That is necessary because a stream works only once.
Short-Circuiting
anyMatch, allMatch, noneMatch, and findFirst can short-circuit, which means they can stop early. anyMatch stops at the first match. allMatch stops at the first element that fails. This saves work on large data.
findFirst returns an Optional, which is a box that may hold a value or be empty. Here, orElse("none") gives a default when the box is empty. A later chapter explains Optional fully.
Exercise
Given List<Integer> nums = List.of(3, 8, 12, 5);, write one expression that returns true if any number is greater than 10, and another that counts the even numbers.
Show answer
nums.stream().anyMatch(n -> n > 10) returns true. nums.stream().filter(n -> n % 2 == 0).count() returns 2, because 8 and 12 are even.
Exercise
What does List.of("kiwi", "lime").stream().filter(s -> s.startsWith("z")).findFirst().orElse("none") return, and why?
Show answer
It returns "none". No element starts with "z", so findFirst returns an empty Optional, and orElse supplies the default.