Chapter 9. Working with laziness

 

This chapter covers

  • Understanding the importance of laziness
  • Implementing laziness in Java
  • Creating a lazy list data structure: the Stream
  • Optimizing lazy lists by memoizing evaluated values
  • Handling infinite streams

Some languages are said to be lazy, while others are not. Does this mean that some languages work harder than others? Not at all. Laziness is opposed to strictness. It has nothing to do with how hard a language can work, although you could sometimes think of lazy languages as languages that don’t require the programmer to work as hard as they must with strict ones.

Laziness, as you’ll see, has many advantages for some specific problems, such as composing infinite data structures and evaluating error conditions.

9.1. Understanding strictness and laziness

When applied to method arguments, strictness means that arguments are evaluated as soon as they’re received by the method. Laziness means that arguments are evaluated only when they’re needed.

Of course, strictness and laziness apply not only to method arguments, but to everything. For example, consider the following declaration:

int x = 2 + 3;

Here, x is immediately evaluated to 5 because Java is a strict language; it performs the addition immediately. Let’s look at another example:

int x = getValue();

9.2. Implementing laziness

9.3. Things you can’t do without laziness

9.4. Why not use the Java 8 Stream?

9.5. Creating a lazy list data structure

9.6. The true essence of laziness

9.7. Handling infinite streams

9.8. Avoiding null references and mutable fields

9.9. Summary