Java IntStream iterate vs generate when to use what?
Note how their signatures are different:
generate
takes aIntSupplier
, which means that you are supposed to generate ints without being given anything. Example usages include creating a constant stream of the same integer, creating a stream of random integers. Notice how each element in the stream do not depend on the previous element.iterate
takes aseed
and aIntUnaryOperator
, which means that you are supposed to generate each element based on the previous element. This is useful for creating a inductively defined sequence, for example. In this case, each element is supposed to depend on the previous one.
IntStream.iterate
returns an orderedIntStream
on the other handIntStream.generate
returns an unorderedIntStream
which can help in speeding up parallel stream pipelines.IntStream.generate
are preferred to generate random or constant values as specified in the Javadoc, I would guess most likely for the characteristics of the stream returned.