Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java IntStream iterate vs generate when to use what?

Tags:

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

like image 986
J.J. Beam Avatar asked Oct 14 '19 08:10

J.J. Beam


People also ask

Why do we use IntStream in Java?

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.

How does IntStream range () work?

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 .

Which method is used to iterate over each element of the stream?

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.

What is the difference between for loop and stream in Java?

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.


1 Answers

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.

like image 90
Sweeper Avatar answered Sep 19 '22 10:09

Sweeper