Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Laziness of stream iterators

Java 23 has recently improve the laziness of streams (https://bugs.openjdk.org/browse/JDK-8196106), allowing this code to work:

Stream.of(1)
.flatMap(c -> Stream.generate(() -> 1).flatMap(x -> Stream.generate(() -> x)))
.limit(5)
.forEach(System.out::println);

However, this still doesn't work:

Stream.of(1)
.flatMap(c -> Stream.generate(() -> 1).flatMap(x -> Stream.generate(() -> x)))
.iterator()
.next()
  1. I understand that iterators are described as an “escape hatch”, but shouldn't iterators on infinite streams work nonetheless?
  2. My need is to use the first element of a stream and later maybe more. How can I do that without the “escape hatch” of iterators?
Comments
Post Details
Added on Nov 27 2024
1 comment
202 views