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()
- I understand that iterators are described as an “escape hatch”, but shouldn't iterators on infinite streams work nonetheless?
- 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?