Why stream don't throw RuntimeException? [duplicate]
Solution 1:
As it says in the Javadoc of the java.util.stream
package (emphasis added):
Intermediate operations return a new stream. They are always lazy; executing an intermediate operation such as filter() does not actually perform any filtering, but instead creates a new stream that, when traversed, contains the elements of the initial stream that match the given predicate. Traversal of the pipeline source does not begin until the terminal operation of the pipeline is executed.
map
is an intermediate operation, and you don't have a terminal operation. As such, the pipeline source is not traversed.
Change map
to forEach
(and remove the return
):
nums.stream().forEach((num) -> {
test();
});
(I assume also that nums
is non-empty).