In your first code sample, you are assigning the lambda expression () -> msg
to each element of the tasks
array.
However, in the second example, you are assigning the lambda expression () -> msg
to a temporary variable t
with type Callable<String>
. The intention of Stream#forEach
is to pass the elements of the stream to a consumer that uses the elements in some way. If you assign to the consumer's parameter in some way, the source of the stream will not reflect that. Such an operation might not even make any sense:
IntStream.range(1,10).filter((x) -> (x % 2 == 0)).forEach((x) -> {++x;});
This ties to a general theme of Java streams: they are unidirectional pipelines for producing, transforming, filtering, and consuming data. As data flows from the Arrays.stream
supplier, it can only flow in one direction, into the consumer (forEach
); changes made downstream will not propagate back upstream.