![]() |
VOOZH | about |
In Java, the IntStream.generate() method is part of the java.util.stream.IntStream class. This method is used to generate an infinite sequential and unordered stream of int values. This method takes IntSupplier as an argument.
Note: It is commonly used for generating random numbers, constant streams, or any kind of data where we need a sequence of numbers that follows a particular pattern.
static IntStream generate(IntSupplier s)
Note: IntStream is the type of stream that will hold primitive int values.
The generate() method keeps on calling the IntSupplier getAsInt() method to create a new int each time. It will keep on generating values unless we set a limit. This method is useful when we need to generate random numbers and endless sequences or repeating patterns.
Now, we are going to discuss some examples, for better understanding.
Example 1: In this example, we will generate a stream of random number.
2805 4606 6570 2748 6968 2772 5052
Explanation: Here, we are using IntStream.generate(() -> (int)(Math.random() * 10000), it will create an infinite stream of random integer. Each number is generated by picking a random decimal between 0 and 1 and then multiply by 10,000, which gives a number between 0 and 999. We are using stream.limit(7) so that we can take only the 7 number as the stream is infinite that's why we are setting the limit, if we do not set the limit the program will run forever and then we are printing all the seven random number one by one.
Example 2: In this example, we will generate a stream of constant values.
5 5 5 5 5 5 5 5 5 5
Explanation: Here, we are using IntStream.generate(() -> 5), it will create a stream where every element is the constant value 5. The lambda expression () -> 5 will return the number 5 each time. We are using stream.limit(10), this will limits the stream just to 10 elements, if we do not set the limit then the program will keep on generating the number 5 infinitely and then we are printing the number 5, ten times.