Generate infinite Stream of Integers in Java
This post will discuss how to generate an infinite stream of integers in Java.
Until now, many of you have generated and operated only on the finite streams. This post provides an overview of infinite streams in Java, which is nothing but a sequential unordered stream that doesn’t end.
If a stream in Java is not properly bounded, then calling any terminal operation upon it may cause the program to enter into an endless state. To avoid it, ensure that the stream is properly bounded or truncate the stream to return only the first few elements in the encounter order.
There are many ways to generate an infinite sequential unordered stream in Java, which are discussed below:
1. Using IntStream.iterate() method
The most common approach to generate an infinite sequential stream is to call the iterate() method provided by the IntStream interface. It takes two parameters – an initial value, also known as the seed, which would be the first element of the stream, and a function to be applied to the previous element to produce a new element. In other words, the value of the next element in the stream will be determined by the result of applying that method to the previous element of the stream.
Now let’s generate an infinite stream starting from 0, whose each successive element is one more than the previous element.
|
1 2 |
IntStream.iterate(0, i -> i + 1) .forEach(System.out::println); // 0, 1, 2, 3, 4, 5, … |
The above code is equivalent to the following infinite for-loop:
|
1 2 3 |
for (int i = 0; ;i++) { System.out.println(i); } |
We can call the limit() method to put a constraint on the size of the stream. We can also call the skip() method to discard the first few stream elements. This is demonstrated below:
|
1 2 3 4 5 |
// Skip the first 5 elements of the infinite stream and print the next 10 elements IntStream.iterate(0, i -> i + 1) .skip(5) .limit(10) .forEach(System.out::println); // 5, 6, 7, … , 13, 14 |
2. Using Random.ints() method
We know that Java provides the Random class to generate a stream of pseudorandom numbers. To generate a stream of random int values, we can use the ints() method of the Random class, as shown below:
|
1 2 |
Random random = new Random(); random.ints().forEach(System.out::println); |
The random class has another overloaded version of the ints method, ints(start, end + 1), where we can also specify the range of returned random values.
|
1 2 3 4 5 6 |
Random random = new Random(); int start = 0, end = 10; // generate an infinite stream of random integers between 0 and 10 random.ints(start, end + 1).forEach(System.out::println); |
We can also put a limit on the total number of random values returned by ints() by passing the total number of values to generate as an argument, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import java.util.Random; class Main { public static void main(String[] args) { // Get an instance of `Random` class Random random = new Random(); int limit = 5; int start = 0, end = 10; // generate a stream of 5 random integers random.ints(limit).forEach(System.out::println); // generate a stream of 5 random integers between 0 and 10 random.ints(limit, start, end + 1).forEach(System.out::println); } } |
3. Using IntStream.generate() method
The IntStream interface also has another method, generate() to generate an infinite stream. This method takes a Supplier<T> to generate new values, rather than a method that applies successively to the previous value.
There are many suppliers provided by Java that we can use, as shown below. The first two suppliers generate a stream of random elements, and the last two generates a stream of consecutive integers that are increasing.
⮚ ThreadLocalRandom.current().nextInt()
|
1 2 |
IntStream.generate(ThreadLocalRandom.current()::nextInt) .forEach(System.out::println); |
⮚ Random.nextInt()
|
1 2 3 |
Random random = new Random(); IntStream.generate(random::nextInt) .forEach(System.out::println); |
⮚ Using AtomicInteger.incrementAndGet()
|
1 2 3 |
AtomicInteger counter = new AtomicInteger(); IntStream.generate(counter::incrementAndGet) .forEach(System.out::println); // 1, 2, 3, 4, 5, … |
⮚ PrimitiveIterator.OfInt nextInt()
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import java.util.PrimitiveIterator; import java.util.stream.IntStream; class Main { public static void main(String[] args) { PrimitiveIterator.OfInt itr = new PrimitiveIterator.OfInt() { private int counter = 1; @Override public int nextInt() { return counter++; } @Override public boolean hasNext() { return (counter == Integer.MAX_VALUE); } }; IntStream.generate(itr::nextInt) .forEach(System.out::println); // 1, 2, 3, 4, 5, … } } |
That’s all about generating an infinite Stream of Integers in Java.
Exercise: Create an infinite stream of Doubles in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)