Junior — Middle
Can the terminal method be applied multiple times to the same stream in Java's Stream API?
sobes.tech AI
Answer from AI
No, the terminal method in Java Stream API can only be applied once to a single stream. After calling a terminal method, the stream is considered closed, and reusing the same stream will result in an IllegalStateException.
If you need to perform multiple operations, you should create a new stream from the original collection or data source.
Example:
List<String> list = Arrays.asList("a", "b", "c");
Stream<String> stream = list.stream();
long count = stream.count(); // terminal method
// stream.forEach(System.out::println); // will throw IllegalStateException
// Correct:
list.stream().forEach(System.out::println);