IntStream generate() method in Java

Java 8Object Oriented ProgrammingProgramming

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
raja
Updated on 30-Jul-2019 22:30:25

Advertisements