August 14, 2022

Java – Stream has already been operated upon or closed

In Java 8, Stream cannot be reused, once it is consumed or used, the stream will be closed. If we reuse the stream it will throw an IllegalStateException, saying “stream is closed”. For whatever reason, you really want to reuse a Stream, try the following Supplier solution. Each Supplier.get() will return a new stream.

Java – Stream has already been operated upon or closed Read More

Java 8 – Should we close the Stream after use?

Streams have a BaseStream.close() method and implement AutoCloseable, but nearly all stream instances do not actually need to be closed after use. Generally, only streams whose source is an IO channel (such as those returned by Files.lines(Path, Charset)) will require closing. Most streams are backed by collections, arrays, or generating functions, which require no special resource management. (If a stream does require closing, it can be declared as a resource in a try-with-resources statement.)

Java 8 – Should we close the Stream after use? Read More

Java 8 Stream – The peek() is not working with count()?

Many examples are using the .count() as the terminal operation for .peek(). However, for Java 9 and above, the peek() may print nothing. Since Java 9, if JDK compiler is able computing the count directly from the stream (optimization in Java 9), it didn’t traverse the stream, so there is no need to run peek() at all. To force the peek() to run, just alter some elements with filter() or switch to another terminal operation like collect(). Be careful of mixing .peek() with .count(), the peek() may not work as expected in Java 9 and above.

Java 8 Stream – The peek() is not working with count()? Read More