Generate Infinite Stream of Integers in Java using IntStream.generate()

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 28-Mar-2019 11:28:36
Advertisements