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


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
.
.
.
raja
Published on 03-Apr-2019 12:58:26
Advertisements