Java IntStream iterate vs generate when to use what?

J.J. Beam :

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

Sweeper :

Note how their signatures are different:

  • generate takes a IntSupplier, 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 a seed and a IntUnaryOperator, 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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=304390&siteId=1