Machine-translated by Google. Questions are authored in English.
Top

Discussion

Consider what happens when an element is added to a collection during a stream traversal of it. Which statement is correct?

  • A.The stream restarts so the traversal always sees a consistent snapshot.
  • B.The behaviour is undefined and may throw ConcurrentModificationException.
  • C.The new element is guaranteed to be included in the traversal.
  • D.The new element is guaranteed to be excluded from the traversal.

Answer: B

A stream over a plain collection reads it lazily, so modifying the source while the pipeline runs leaves the result undefined in the same way as modifying it during a for-each. The remedy is to collect into a new collection rather than mutate the one being read.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.