IntStream generate() method in Java


The generate() method in the IntStream class returns an infinite sequential unordered stream where each element is generated by the provided IntSupplier.

The syntax is as follows

static IntStream generate(IntSupplier i)

Here, i is the IntSupplier for generated elements. The IntSupplier represents a supplier of int-valued results.

The following is an example to implement IntStream generate() method in Java. We have used the limit() method here as well to limit the number of elements we want from the stream

Example

 Live Demo

import java.util.*;
import java.util.stream.IntStream;
public class Demo {
   public static void main(String[] args) {
      IntStream intStream = IntStream.generate(()
      -> { return (int)(Math.random() * 100); });
      intStream.limit(3).forEach(System.out::println);
   }
}

Output

7
26
22

Updated on: 30-Jul-2019

323 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements