Why do I get OutOfMemoryError for the following code?
Stream.from(1).filter(n => (1 to 20).forall(x => n % x == 0)).head
Why do I get OutOfMemoryError for the following code?
Stream.from(1).filter(n => (1 to 20).forall(x => n % x == 0)).head
Streams have some limitations on the JVM. The problem you are seeing here is that the Stream you are creating with Stream.from(1)
is put on the stack and thus the JVM refuses to garbage collect it. The predicate you are passing to the filter
call lets the Stream grow to 232792560
elements.
If you use an Iterator
you can work around this limitation:
Iterator.from(1).filter(n => (1 to 20).forall(x => n % x == 0)).next
Streams are lazily evaluated, but they store the results of their evaluations. Thus, unless you want to traverse through them multiple times, you should use Iterator
instead.