Home / JAVA Complete Reference by Examples / Streams / How to use Stream generate method using Lamdba expression in Java 8 Example
How to use Stream generate method using Lamdba expression in Java 8 Example
732 views.
package com.learnbyexamples.streams;

import java.util.Arrays;
import java.util.stream.Stream;


/*
 * Program to generate 10 random numbers.
 * using Stream.generate method.
 */
public class E004_GenerateMethodInStream {
    public static void main(String[] args) {
        //Genereate a dynamic stream using generate and set the limit to 10.
        //generate(Supplier<T> -> T get())
        Stream<Double> randomNumbers = Stream.generate(Math::random).limit(10);
        
        //Convert stream into array.
        Double[] fiftyNumbers = randomNumbers.toArray(size -> new Double[size]);
        
        //Prints fiftyNumbers
        System.out.println(Arrays.toString(fiftyNumbers));
    }
}
Output
[0.7566315783650638, 0.445924696840878, 0.22506903087981456, 0.8174990692539644, 0.8780038533446746, 0.9613262385412967, 0.6501920222364149, 0.6500519748392767, 0.8949833741073414, 0.9718500909796753]
Related Examples
   How to filter an List stream using Lambda expression in Java 8 by Example
   How to filter an Array stream using Lambda expression in Java 8 by Example
   How to filter an Map stream using Lambda expression in Java 8 by Example
   How to use Stream generate method using Lamdba expression in Java 8 Example
   How to read a file line by line using stream in Java 8 by Example
   How to split string into stream in Java 8 by Example
   How to transform stream elements using map in Java 8 by Example
   How to use flatMap stream method in Java 8 by Example
Copyright © 2016 Learn by Examples, All rights reserved