It seems IntStream.iterate
is just a lightweight ordered version for IntStream.generate
. Is it true? If not, what is the core difference?
An IntStream interface extends the BaseStream interface in Java 8. It is a sequence of primitive int-value elements and a specialized stream for manipulating int values. We can also use the IntStream interface to iterate the elements of a collection in lambda expressions and method references.
range() method generates a stream of numbers starting from start value but stops before reaching the end value, i.e start value is inclusive and end value is exclusive. Example: IntStream. range(1,5) generates a stream of ' 1,2,3,4 ' of type int .
Java Stream forEach() method is used to iterate over all the elements of the given Stream and to perform an Consumer action on each element of the Stream.
The short version basically is, if you have a small list; for loops perform better, if you have a huge list; a parallel stream will perform better. And since parallel streams have quite a bit of overhead, it is not advised to use these unless you are sure it is worth the overhead.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With