Terminal operations
A terminal operation is the step that asks a stream for its answer: a number, a boolean, an optional element or a side effect. Each one pulls the elements through the pipeline, and some of them stop as soon as the answer is known. This lesson runs the whole set on one small list, so the differences are visible in four lines of output each.
The terminal operations
Eight of them on the list 3, 1, 4, 1, 5. Two answer an Optional, three answer a boolean, one answers a long, one a value and one nothing:
import java.util.List;
import java.util.Optional;
public class Terminals {
public static void main(String[] args) {
List<Integer> numbers = List.of(3, 1, 4, 1, 5);
System.out.println("count " + numbers.stream().count());
System.out.println("findFirst " + numbers.stream().findFirst().orElse(-1));
System.out.println("anyMatch > 4: " + numbers.stream().anyMatch(n -> n > 4));
System.out.println("allMatch > 0: " + numbers.stream().allMatch(n -> n > 0));
System.out.println("noneMatch < 0: " + numbers.stream().noneMatch(n -> n < 0));
System.out.println("max " + numbers.stream().max(Integer::compare).orElseThrow());
System.out.println("min " + numbers.stream().min(Integer::compare).orElseThrow());
Optional<Integer> empty = List.<Integer>of().stream().findFirst();
System.out.println("empty findFirst " + empty.isPresent());
numbers.stream().forEach(n -> System.out.print(n + " "));
System.out.println();
}
}
javac -Xlint:all Terminals.java
java Terminals
count 5
findFirst 3
anyMatch > 4: true
allMatch > 0: true
noneMatch < 0: true
max 5
min 1
empty findFirst false
3 1 4 1 5
count answers a long, not an int, because a stream may be longer than an array. The three match operations answer a boolean and read as their names: any element matches, all of them do, none does. The last line ends with a space because the body prints one after every element, which is why the empty println follows.
reduce
reduce folds the elements into one value with a binary operation. With an identity it always answers a value; without one it answers an Optional, because an empty stream has nothing to fold:
import java.util.List;
import java.util.Optional;
public class Reduce {
public static void main(String[] args) {
List<Integer> numbers = List.of(1, 2, 3, 4);
System.out.println(numbers.stream().reduce(0, Integer::sum));
System.out.println(numbers.stream().reduce(1, (a, b) -> a * b));
Optional<Integer> sum = numbers.stream().reduce(Integer::sum);
System.out.println("no identity: " + sum.orElse(-1));
List<String> words = List.of("a", "b", "c");
System.out.println(words.stream().reduce("", (a, b) -> a + b));
System.out.println(words.stream().reduce((a, b) -> a + "-" + b).orElse(""));
System.out.println(List.<Integer>of().stream().reduce(0, Integer::sum));
System.out.println(List.<Integer>of().stream().reduce(Integer::sum).isEmpty());
}
}
javac -Xlint:all Reduce.java
java Reduce
10
24
no identity: 10
abc
a-b-c
0
true
The second line multiplies with the identity 1, which is what makes the product of four numbers 24. The last two lines are the difference: the fold with an identity answers the identity for an empty stream, and the fold without one answers an empty optional. A join with Collectors.joining is the better way to build a string, which is the next lesson.
Short-circuiting
findFirst, anyMatch and findAny stop as soon as they have an answer, so a lazy step before them runs only as often as it must. The program prints inside the predicates to show how far the stream walked:
import java.util.List;
public class Short {
public static void main(String[] args) {
List<String> words = List.of("fig", "apple", "pear");
String first = words.stream()
.filter(w -> {
System.out.println("testing " + w);
return w.length() > 3;
})
.findFirst()
.orElse("none");
System.out.println("found " + first);
System.out.println(words.stream().anyMatch(w -> {
System.out.println("any " + w);
return w.startsWith("p");
}));
}
}
javac -Xlint:all Short.java
java Short
testing fig
testing apple
found apple
any fig
any apple
any pear
true
The filter tested two words and stopped at the first one that passed, so pear was never examined. The second pipeline tested all three, because the word that matches is the last one: the short circuit saves the work only when the answer arrives early. That is why a stream over an infinite source is safe with limit and a match operation.
An empty stream
Every terminal operation has a defined answer for an empty stream: count is zero, the matches are false, false and true, findFirst and max are empty optionals, and forEach does nothing. The two booleans that surprise are allMatch and noneMatch, which are both true for no elements, because nothing contradicts them.
That is the same rule as the empty product in reduce: the identity is the answer when there is nothing to combine. A program that distinguishes "no elements" from "the answer is false" needs findFirst and its optional, not a match.
Exercises
- Count the words of Terminals that are longer than three letters.
- Use reduce to find the longest word of a list and print it.
- Add a match that tests a condition no element satisfies and confirm the whole stream is read.
- Print the count of an empty stream and the value of allMatch on it.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which terminal operation answers a long?
Answer
count
A stream may be longer than an int, so count answers a long.
-
What does
reduceanswer without an identity?Answer
An Optional, empty when the stream is empty
There is no value to answer when there are no elements, so the result is optional.
-
Which operations stop as soon as the answer is known?
Answer
findFirst, anyMatch and findAny
A match needs one element to answer true, and a find needs one element at all.
-
What does this program print?
import java.util.List; public class Q1 { public static void main(String[] args) { List<Integer> numbers = List.of(2, 4, 6); System.out.println(numbers.stream().count()); System.out.println(numbers.stream().allMatch(n -> n % 2 == 0)); } }Answer
3 / true
All three numbers are even, so allMatch answers true.
-
What does this program print?
import java.util.List; public class Q2 { public static void main(String[] args) { List<Integer> numbers = List.of(1, 2, 3); System.out.println(numbers.stream().reduce(0, (a, b) -> a + b)); System.out.println(numbers.stream().reduce(10, (a, b) -> a + b)); } }Answer
6 / 16
The identity is the starting value, so the second sum starts at ten.
-
What does this program print?
import java.util.List; public class Q3 { public static void main(String[] args) { List<String> words = List.of("a", "bb", "ccc"); System.out.println(words.stream().max(String::compareTo).orElse("none")); } }Answer
ccc
The natural order of strings is alphabetical by length here, and ccc is the greatest.
-
What does this program print?
import java.util.List; public class Q4 { public static void main(String[] args) { List<Integer> numbers = List.of(1, 2, 3); System.out.println(numbers.stream().noneMatch(n -> n > 5)); System.out.println(List.<Integer>of().stream().noneMatch(n -> n > 5)); } }Answer
true / true
No element of either stream is greater than five, so noneMatch is true for both.
-
What does this program print?
import java.util.List; public class Q5 { public static void main(String[] args) { List<String> words = List.of("a", "bb"); words.stream().forEach(w -> System.out.print(w)); System.out.println(); System.out.println(words.stream().findFirst().orElse("none")); } }Answer
abb then a
forEach prints both without a separator, and findFirst answers the first element.
-
What does
allMatchanswer for an empty stream?Answer
true, because no element contradicts it
The universal claim holds when there is nothing to check, which is the same rule as an empty product.
-
Why did the filter of Short test only two of the three words?
Answer
findFirst stopped the stream at the first match
A short-circuiting terminal operation ends the walk as soon as it can answer.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev