Java core learning path Level 1 This level · 32 of 34
Easy java spring

collect invoked twice on the same stream?

The 30 second answer

The second call throws IllegalStateException saying the stream has already been operated upon or closed. Streams are single-use. Recreate the stream from the source, wrap creation in a Supplier, or collect once and reuse the result. If you need two results in one pass, use Collectors teeing.

Could you say this in an interview?

Second call throws **IllegalStateException: stream has already been operated upon or closed**. Streams are single-use. Recreate from the source, or use a Supplier<Stream<T>>, or collect once and reuse the result (teeing if you need two results in one pass).

Sources (2)
  1. java.util.stream package — "Stream operations and pipelines"docs.oracle.com
  2. Collectors.teeingdocs.oracle.com
Previous
Next