

Optional anyElement = elements.stream().findAny() So to make the previous code work properly, some changes should be made: List elements = We designed streams to apply a finite sequence of operations to the source of elements in a functional style, not to store elements. So it is very important to remember that Java 8 streams can't be reused. However, an attempt to reuse the same reference after calling the terminal operation will trigger the IllegalStateException: Optional firstElement = stream.findFirst() Īs the IllegalStateException is a RuntimeException, a compiler will not signalize about a problem.

Besides its unnecessary verbosity, technically the following code is valid: Stream stream = To demonstrate this, we will forget for a while that the best practice is to chain the sequence of operation.
