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
.
.
.

Updated on: 30-Jul-2019

126 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements