How to use Stream generate method using Lamdba expression in Java 8 Example 2476 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
|
|