Tutorialspoint

How to generate Infinite Stream of Integers in Java using IntStream.iterate()


1 Answer
Nancy Den

To generate an infinite stream of integer, use the IntStream.iterate(). The method is used to iterator an IntStream.

Import the following package for the IntStream class in Java:

import java.util.stream.IntStream;

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

Example

import java.util.stream.IntStream;
public class Main {
   public static void main(String[] args) {
      IntStream.iterate(0, k -> k + 2).forEach(System.out::println);
   }
}

Here is the output that displays integers infinitely:

0
2
4
6
8
10
12
.
.
.

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.