Sobes.tech
Junior — Middle

When does the Stream initialize when using the Stream API?

sobes.tech AI

Answer from AI

Initialization of a Stream in Java occurs at the moment of calling a terminal operation. Until then, operations on the Stream are lazy and not executed.

That is, when you create a Stream and apply intermediate operations (for example, filter(), map()), they only form a processing chain but do not execute computations.

Example:

List<String> list = Arrays.asList("a", "b", "c");
Stream<String> stream = list.stream()
    .filter(s -> s.startsWith("a"))
    .map(String::toUpperCase);
// Nothing happens here

List<String> result = stream.collect(Collectors.toList()); // Terminal operation
// Processing of elements occurs here

Thus, the Stream is initialized and begins data processing only when a terminal operation is called, such as collect(), forEach(), reduce(), etc.