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.
The sum() method is available in the primitive int-value stream like IntStream, not Stream
Few examples to show you how to sort a List with stream.sorted(): Sort a List with Comparator.naturalOrder(), Sort a List with Comparator.reverseOrder(), Sort a List user objects.
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.)
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.
In Java 8, you can use Files.lines to read file as Stream. A new method lines() has been added since 1.8, it lets BufferedReader returns content as Stream.
In Java 8, we can use the Stream.reduce() to sum a list of BigDecimal. Java example to sum a list of BigDecimal values, using a normal for loop and a stream.reduce(). We can use technique of Map and Reduce to Sum all BigDecimal from a list of Invoices.