简体   繁体   中英

Why is the stream with a limit infinite?

I have run the following code in Eclipse:

Stream.generate(() -> "Elsa")
      .filter(n -> n.length() ==4)
      .sorted()
      .limit(2)
      .forEach(System.out::println);

The output is:

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

What I was expecting since the limit is two:

Elsa
Elsa

Can someone please explain why this is an infinite stream?

The first thing is that Stream::generate creates an infinite stream. That's why the stream is initially infinite.

You limit the stream to two elements by using Stream::limit , which would make it finite.

However, the problem is that you call sorted() , which tries to consume the whole stream. You need to limit the stream before you sort:

Stream.generate(() -> "Elsa")
    .filter(n -> n.length() == 4)
    .limit(2)
    .sorted()
    .forEach(System.out::println);

The documentation says that Stream::sorted() "is a stateful intermediate operation" . The Streams documentation about a stateful intermediate operation explains it very well :

Stateful operations may need to process the entire input before producing a result. For example, one cannot produce any results from sorting a stream until one has seen all elements of the stream .

Emphasis mine.

There it is. Also note that for all Stream operations, their operation type is mentioned in the Javadocs.

Can someone please explain why this is an infinite stream?

Because the javadoc says that is precisely what Stream.generate() creates:

Returns an infinite sequential unordered stream where each element is generated by the provided Supplier

Then when you combine that with sorted() , you tell it to start a sort on an infinite sequence which will obviously cause the JVM to run out of memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM