Generate Infinite Stream of Integers in Java Using IntStream.generate



You can also generate Infinite Stream of Integers in Java with IntStream.generate() method. Here, we have used the Random class to get the list of random integers:

Random r = new Random();

After that use IntStream.generate() and the nextInt() method gets the next random integer:

IntStream.generate(r::nextInt)

The following is an example displaying how to generate Infinite Stream of Integers with IntStream.generate() in Java:

import java.util.stream.*;
import java.util.*;
public class Main {
   public static void main(String[] args) {
      Random r = new Random();
      IntStream.generate(r::nextInt).forEach(System.out::println);
   }
}

Here is the output:

565757777
3535363636
9879879879
-686549988
Updated on: 2019-07-30T22:30:25+05:30

148 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements