with - stream api in java 8 javatpoint




Java IntStream iterate vs generate when to use what? (2)

  1. IntStream.iterate returns an ordered IntStream on the other hand IntStream.generate returns an unordered IntStream which can help in speeding up parallel stream pipelines.

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

It seems IntStream.iterate is just a lightweight ordered version for IntStream.generate . Is it true? If not, what is the core difference?


Aside from order, also the usage is a bit different. Let's look at the method signatures:

  • iterate(int seed, IntUnaryOperator f)
  • generate(IntSupplier s)

Iterate has explicitly given starting value as parameter and unary operator which is used to generate next value from previous. Here operator can easily be immutable without internal state and can be reused in multiple places in parallel without any issue.

Generate uses supplier. Those can either provide constant or random numbers or need to have internal state to provide series like (1, 2, 3, ...).







java-stream