Java - Generate primitive values by generate() method from primitive type stream

Introduction

The following code prints five random integers using the generate() static method of the IntStream interface:

Demo

import java.util.Random;
import java.util.stream.IntStream;

public class Main {
  public static void main(String[] args) {
    IntStream.generate(new Random()::nextInt).limit(5).forEach(System.out::println);

  }//from  ww  w.  j  a  v a2s  .c o  m
}

Result

To generate an infinite stream of a repeating value:

IntStream zeroes = IntStream.generate(() -> 0);

Related Topic