Why do I get OutOfMemoryError for the following code?
Stream.from(1).filter(n => (1 to 20).forall(x => n % x == 0)).head
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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 thefiltercall lets the Stream grow to232792560elements.If you use an
Iteratoryou can work around this limitation: