Sub topic 6
Getting Results: forEach, count, anyMatch, and findFirst
A stream pipeline does nothing until it reaches its last step. That last step is the terminal operation. A terminal operation is the method that ends the pipeline and produces a result or an action. Until you call one, your filter and map steps are only a plan.
This chapter covers the terminal operations you will use most often:
forEachruns an action on each element.counttells you how many elements there are.anyMatch,allMatch, andnoneMatchanswer yes-or-no questions.findFirstandfindAnypick out one element.
Collecting results into lists and maps comes later, in its own chapter.
Why Terminal Operations Matter
A terminal operation does two jobs. It starts the work: elements flow from the source through each step. It also gives you something back. That might be a number, a true or false, a single element, or just printed output.
After a terminal operation runs, the stream is consumed. That means it is used up, and you cannot call another terminal operation on it. If you need a second answer, build a new stream from the source.
forEach: Do Something with Each Element
forEach takes a lambda and runs it once for every element that reaches the end of the pipeline. It returns nothing; its return type is void. You use it for actions such as printing.
count returns the number of elements as a long. A long is a whole-number type that can hold much larger values than int.
import java.util.List;
public class ForEachCountExample {
public static void main(String[] args) {
List<String> fruits = List.of("apple", "banana", "cherry", "avocado");
fruits.stream()
.filter(f -> f.startsWith("a"))
.forEach(f -> System.out.println(f));
// apple
// avocado
long longNames = fruits.stream()
.filter(f -> f.length() > 5)
.count();
System.out.println(longNames); // 3
}
}The lambda f -> System.out.println(f) can also be written as the method reference System.out::println. Both do the same thing.
forEach and Order
For a normal stream built from a list, forEach visits elements in list order. Parallel streams, covered at the end of the tutorial, behave differently: forEach may visit elements in any order. If order matters there, use forEachOrdered. For now, plain forEach is fine.
count: How Many?
count is simple, but it has one surprise.
When a filter is in the pipeline, Java cannot know the answer ahead of time, so every element is checked.
anyMatch, allMatch, and noneMatch: Yes-or-No Questions
These three methods each take a predicate. A predicate is a lambda that returns true or false for one element, such as n -> n > 40. Each method returns a boolean.
| Method | Returns true when | Example question |
|---|---|---|
| `anyMatch` | at least one element passes | Is any number over 40? |
| `allMatch` | every element passes | Are all numbers positive? |
| `noneMatch` | no element passes | Is no number negative? |
import java.util.List;
public class MatchExample {
public static void main(String[] args) {
List<Integer> numbers = List.of(4, 8, 15, 16, 23, 42);
System.out.println(numbers.stream().anyMatch(n -> n > 40)); // true
System.out.println(numbers.stream().allMatch(n -> n > 0)); // true
System.out.println(numbers.stream().allMatch(n -> n % 2 == 0)); // false
System.out.println(numbers.stream().noneMatch(n -> n < 0)); // true
}
}Each line creates a new stream with numbers.stream(). That is required, because each match call consumes its stream.
They Stop Early
These methods are short-circuiting. A short-circuiting operation can stop before it looks at every element. anyMatch stops at the first element that passes, because the answer is already true. allMatch stops at the first element that fails. The next program shows this:
import java.util.List;
public class ShortCircuitExample {
public static void main(String[] args) {
List<Integer> numbers = List.of(3, 7, 50, 9, 12);
boolean found = numbers.stream()
.anyMatch(n -> {
System.out.println("checking " + n);
return n > 40;
});
System.out.println(found);
// checking 3
// checking 7
// checking 50
// true
}
}The numbers 9 and 12 are never checked. On a large list, stopping early saves real time. A later chapter explains why streams can do this.
The Empty Stream Edge Case
What happens when the stream has no elements? The answers can look odd at first:
| Method | Result on an empty stream |
|---|---|
| `anyMatch` | `false` |
| `allMatch` | `true` |
| `noneMatch` | `true` |
allMatch returns true because no element failed. This is called being "vacuously true." It can cause bugs. Suppose you check orders.stream().allMatch(o -> o.isPaid()) when there are no orders. The answer is true, which may not be what you want. If an empty list should count as a failure, check isEmpty() first.
import java.util.List;
public class EmptyMatchExample {
public static void main(String[] args) {
List<Integer> empty = List.of();
System.out.println(empty.stream().anyMatch(n -> n > 0)); // false
System.out.println(empty.stream().allMatch(n -> n > 0)); // true
System.out.println(empty.stream().noneMatch(n -> n > 0)); // true
}
}findFirst and findAny: Get One Element
findFirst returns the first element that reaches the end of the pipeline. Often there is a filter before it, so you get the first element that matches.
The stream might have no elements left, so findFirst cannot always return an element. It returns an Optional instead. An Optional is a box that holds either one value or nothing. The next chapter on Optional covers it fully. For now, one method is enough: orElse(x) gives you the value if there is one, and x if the box is empty.
import java.util.List;
public class FindExample {
public static void main(String[] args) {
List<String> cities = List.of("Oslo", "Lima", "Paris", "Lyon");
String firstL = cities.stream()
.filter(c -> c.startsWith("L"))
.findFirst()
.orElse("no match");
System.out.println(firstL); // Lima
String firstQ = cities.stream()
.filter(c -> c.startsWith("Q"))
.findFirst()
.orElse("no match");
System.out.println(firstQ); // no match
String any = cities.stream()
.filter(c -> c.length() == 4)
.findAny()
.orElse("no match");
System.out.println(any); // usually Oslo
}
}findFirst also short-circuits. It stops at the first match, so "Paris" and "Lyon" are never checked in the first search.
findFirst or findAny?
findAny returns some matching element, not necessarily the first. On a normal stream it usually returns the first one, but the rules don't promise that. On a parallel stream it can be faster, because any worker thread that finds a match can stop the search. Use findFirst when you need the first one. Use findAny when any match will do.
Summary of Return Types
| Operation | Returns | Short-circuits? |
|---|---|---|
| `forEach` | `void` | No |
| `count` | `long` | No |
| `anyMatch` | `boolean` | Yes |
| `allMatch` | `boolean` | Yes |
| `noneMatch` | `boolean` | Yes |
| `findFirst` | `Optional<T>` | Yes |
| `findAny` | `Optional<T>` | Yes |
Exercises
Exercise
Given List<String> words = List.of("sun", "moon", "star", "sky"), write one statement that counts how many words have exactly three letters. What value does it produce?
Show answer
long n = words.stream().filter(w -> w.length() == 3).count(); The value is 2, because "sun" and "sky" have three letters.
Exercise
You run List.of(5, 10, 15).stream().allMatch(n -> n > 7). How many elements does the predicate check, and what is the result?
Show answer
It checks only one element. 5 fails n > 7, so allMatch stops right away and returns false.
Exercise
A list of users is empty. The code users.stream().allMatch(u -> u.isActive()) returns true. Why, and how would you make an empty list give false instead?
Show answer
allMatch on an empty stream returns true because no element fails the test. To get false for an empty list, write !users.isEmpty() && users.stream().allMatch(u -> u.isActive()).
Exercise
Write a statement that finds the first number greater than 100 in List<Integer> values, or returns -1 if there is none.
Show answer
int result = values.stream().filter(v -> v > 100).findFirst().orElse(-1);