Java Reference
In-Depth Information
is an example of a side effect. All lambdas you've seen so far were side-effect free; they didn't
change any state.
To come back to our Fibonacci tasks, what you need to do now is create an IntSupplier that
maintains in its state the previous value in the series, so getAsInt can use it to calculate the next
element. In addition, it can update the state of the IntSupplier for the next time it's called. The
following code shows how to create an IntSupplier that will return the next Fibonacci element
when it's called:
IntSupplier fib = new IntSupplier(){
private int previous = 0;
private int current = 1;
public int getAsInt(){
int oldPrevious = this.previous;
int nextValue = this.previous + this.current;
this.previous = this.current;
this.current = nextValue;
return oldPrevious;
}
};
IntStream.generate(fib).limit(10).forEach(System.out::println);
In the preceding code you create an instance of IntSupplier. This object has mutable state: it
tracks the previous Fibonacci element and the current Fibonacci element in two instance
variables. The getAsInt method changes the state of the object when it's called so that it
produces new values on each call. In comparison, our approach using iterate was purely
immutable : you didn't modify existing state but were creating new tuples at each iteration.
You'll learn in chapter 7 that you should always prefer an immutable approach in order to
process a stream in parallel and expect a correct result.
Note that because you're dealing with a stream of infinite size, you have to limit its size explicitly
using the operation limit; otherwise, the terminal operation (in this case forEach) will compute
forever. Similarly, you can't sort or reduce an infinite stream because all elements need to be
processed, but this would take forever because the stream is infinite!
 
Search WWH ::




Custom Search