tags:

views:

68

answers:

2

Why do I get OutOfMemoryError for the following code?

Stream.from(1).filter(n => (1 to 20).forall(x => n % x == 0)).head

+7  A: 

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
Moritz
Shame on you for giving away the answer!
Randall Schulz
The answers are available at many places, Randall.
user7854212
Thanks Moritz. /
user7854212
+3  A: 

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.

Rex Kerr
Very informative. Thanks Rex!
user7854212