Java 8 Friday: 10 Subtle Mistakes When Using the Streams API - DZone Performance
1. Accidentally reusing streams
Wanna bet, this will happen to everyone at least once. Like the existing "streams" (e.g. InputStream
), you can consume streams only once. The following code won't work:
IntStream stream = IntStream.of(1, 2); stream.forEach(System.out::println); // That was fun! Let's do it again! stream.forEach(System.out::println);
You'll get a
java.lang.IllegalStateException: stream has already been operated upon or closed
So be careful when consuming your stream. It can be done only once
2. Accidentally creating "infinite" streams
You can create infinite streams quite easily without noticing. Take the following example:
// Will run indefinitely IntStream.iterate(0, i -> i + 1) .forEach(System.out::println);
The whole point of streams is the fact that they can be infinite, if you design them to be. The only problem is, that you might not have wanted that. So, be sure to always put proper limits:
Read full article from Java 8 Friday: 10 Subtle Mistakes When Using the Streams API - DZone Performance
No comments:
Post a Comment