Lazy collections

All these combinators chaining are lovely, but there is a problem. For very large input data structures, this ends up creating intermediate copies.

Let's look at this aspect closely; you'll find that the solution is pretty revealing. Here is the Java code, just to set the stage:

public class LargeLists {
  public static void main(final String[] args) {
    final int take = 5;
    for (int i = 1000, n = 0; i < 1000000 && n < take; ++i) {
      final int j = i + 1;
      final int k = j * 2;
      if (k % 4 != 0) {
        System.out.println(k);
        ++n;
      }
    }
  }
}

Here, we iterate a range of numbers from 1000 to 1000000. And for each number, we add 1 and then multiply the result by 2. If the result is divisible by 4, we discard it. Otherwise, we print the first five numbers ...

Get Scala Functional Programming Patterns now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.