How to use generate in IntStream?

Here is an example to explain how to use generate in IntStream.

Syntax:

Modifier and Type               Method
static IntStream                generate(IntSupplier s)
package com.nourit.java8.Streams.IntStream;

import java.util.stream.IntStream;

public class IntStreamGenerate {

  public static void main(String[] args) {
    System.out.println("---------- Generate Example 1 -----------------");
    // Returns an infinite sequential unordered stream where each element is generated by the provided IntSupplier.
    IntStream intStream1 = IntStream.generate(() -> Double.valueOf(Math.random() * 100).intValue());
    intStream1.limit(5).forEach(System.out::println);
    System.out.println("---------- Generate Example 2 -----------------");
    // Returns an infinite sequential unordered stream where each element is generated by the provided IntSupplier.
    IntStream.generate(()->{return (int)(Math.random()*100);}).limit(5).forEach(System.out::println);
    System.out.println("---------------------------------------");
  }
}

Output:

---------- Generate Example 1 -----------------
13
48
25
64
90
---------- Generate Example 2 -----------------
89
90
5
57
91
---------------------------------------

 

NOUR-IT

IT Training Center for Java and Web technology. If you enjoy and like our tutorials and believe in our mission, Please Subscribe us on Youtube and follow us on Twitter, or befriend us on Facebook or Google Plus.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

*