Today we’ll look at creating generators. In simple terms, a generator is a function which returns the next value in a sequence. Unlike an iterator, it generates the next value when needed, rather than returning the next item of a pre-generated collection. Some languages such as Python support generators natively via keywords such as yield. When a generator’s next value is requested in Python, the generator function continues to run until the next yield statement, where a value is returned. The generator function is able to continue where it left off which can be quite confusing the uninitiated. So how to do something similar in Java?
We saw in the last article that we can use an IntStream to generate a simple set of numbers, but we had to generate them all up front. That’s fine if we know how many we’re going to need. What if we don’t, and we want to be able to get the next whenever we like? This is where a generator comes in.
Let’s choose a simple infinite sequence, the square numbers. In a standard Java implementation we’d end up with something like the following:
public class Squares
{
private int i = 1;
public int next()
{
int thisOne = i++;
return thisOne * thisOne;
}
public static void main(String args[])
{
Squares squareGenerator = new Squares();
System.out.println(squareGenerator.next());
System.out.println(squareGenerator.next());
System.out.println(squareGenerator.next());
}
}
This prints the first three square numbers. Note we could have gone further and implemented this as an iterator.
What we have here is an example of lazy evaluation in a non-functional style. Wikipedia defines lazy evaluation as: ‘In programming language theory, lazy evaluation, or call-by-need is an evaluation strategy which delays the evaluation of an expression until its value is needed’. Lazy evaluation is useful because we don’t need to worry about infinite sequences, performing computationally expensive operations up-front, and about storage.
Let’s expand on the example to allow getting a batch of results. This is easy – create a nextN function which calls next() a number of times and returns the results in say a List:
public class Squares2
{
private int i = 1;
public int next()
{
int thisOne = i++;
return thisOne * thisOne;
}
public List<Integer> nextN(int n)
{
List<Integer> l = new ArrayList<>();
for (int i = 0; i < n; i++)
{
l.add(next());
}
return l;
}
public static void main(String args[])
{
Squares2 squareGenerator = new Squares2();
squareGenerator.nextN(10).forEach(System.out::println);
}
}
A few points:
- Notice in the nextN function there is the empty diamond in the new ArrayList statement. This was added in Java 7 to save having to state the type both on the left and the right hand side; the compiler now works it out.
- List is an Iterable, and Iterable now has a forEach() method which was added in Java 8. We could use stream() as before to create a stream, but if all we want to do is pass the contents to a function forEach() does nicely.
Now, to save having to write nextN for every sequence we make, we could create a new type which extends Iterator providing the nextN function.
The only problem we face here is that we have to save the batch in a list before we can operate on it. Java 8 provides another way. Let’s go back and start again with the following code:
public class Squares3
{
public static void main(String args[])
{
IntStream.rangeClosed(1, 10).map(i -> i * i)
.forEach(System.out::println);
}
}
This uses IntStream to get the indexes of the sequence in a stream and calls map to convert them into their squares. The problem is that to get more squares than the tenth we need to duplicate the pipeline and start it off from the right place. Let’s look at another way without using a range:
public static void main(String args[])
{
IntStream myStream = IntStream.iterate(1, i -> i + 1);
myStream.limit(10).map(i -> i * i)
.forEach(System.out::println);
}
This also generates the first 10 square numbers. This time it uses the iterate function. This takes two parameters, the first is our initial value, and the second is a function defining how to get to the next value from the previous. It’s a good place to use a lambda function. We can even dispense of the map function since we can undo squaring easily in iterate to get what the last index was:
public static void main(String args[])
{
IntStream myStream = IntStream.iterate(1,
i -> ((int) Math.pow(Math.sqrt(i) + 1, 2)));
myStream.limit(10).forEach(System.out::println);
}
This solves one of the problems of having to buffer beforehand. However, we need to use the limit operator on the stream to limit it to 10 items, otherwise it would keep on going. Unfortunately this is a problem, since once we’ve got the 10 the stream is ‘operated on’ and we can’t use it again to generate more. If we try, we get an IllegalStateException. We’d have to create another stream to get more.
So how do we get around the problem of the stream being used up? Instead of using IntStream’s iterate function, we can use generate instead. IntStream’s generate function takes an instance of an IntSupplier. IntSupplier has a getAsInt() function which returns the next int in the sequence which is very much like our next() function. Here is an example that prints the first 20 square numbers in two batches:
public class SquaresGenerator
{
private static class SqSupplier implements IntSupplier
{
int i = 0;
@Override
public int getAsInt()
{
i++;
return i * i;
}
}
public static void main(String args[])
{
SqSupplier sqSupplier = new SqSupplier();
IntStream myStream = IntStream.generate(sqSupplier);
IntStream myStream2 = IntStream.generate(sqSupplier);
myStream.limit(10).forEach(System.out::println);
myStream2.limit(10).forEach(System.out::println);
}
}
Again we’re using limit to stop the stream continuing indefinitely. However unlike last time, although the stream is used up, the generator still survives and can be used again. No buffering needed either, just keeping hold of the supplier. The only downside vs the old Java way is that we have to use Streams to get sequence members, although this comes with other benefits such as parallelism which we’ll see in a later article.
Overall, there are several ways to generate a sequence and which we chose may depend on our needs. Using an IntSupplier is a good way to integrate with the rest of the Java 8 functional programming support.