O'Reilly logo

Scala Functional Programming Patterns by Atul S. Khot

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required