Junior — Middle
Is it possible to apply multiple terminal methods consecutively in a single Stream in Java?
sobes.tech AI
Answer from AI
In Java Stream API, a terminal method is a method that initiates stream processing and returns a result or a side effect, such as collect(), forEach(), reduce(). After calling a terminal method, the stream is considered closed and cannot be used further.
Therefore, applying multiple terminal methods consecutively to the same Stream object is not allowed — this will lead to an IllegalStateException.
If multiple operations need to be performed, a new Stream should be created or intermediate results should be stored.
Example of incorrect usage:
Stream<String> stream = Stream.of("a", "b", "c");
stream.forEach(System.out::println); // terminal method
stream.count(); // will throw IllegalStateException
The correct approach is to create a new Stream for each terminal operation.