流generate(Supplier s)返回無限順序無序流,其中每個元素由提供的供應商生成。這適用於生成恒定流,隨機元素流等。
用法:
static <T> Stream<T> generate(Supplier<T> s) Where, Stream is an interface and T is the type of stream elements. s is the Supplier of generated elements and the return value is a new infinite sequential unordered Stream.
示例1:生成隨機整數流。
// Java code for Stream.generate()
// to generate an infinite sequential
// unordered stream
import java.util.*;
import java.util.stream.Stream;
class GFG {
// Driver code
public static void main(String[] args) {
// using Stream.generate() method
// to generate 5 random Integer values
Stream.generate(new Random()::nextInt)
.limit(5).forEach(System.out::println);
}
}
輸出:
697197501 50139200 321540264 1042847655 -770409472
示例2:生成隨機Double的流。
// Java code for Stream.generate()
// to generate an infinite sequential
// unordered stream
import java.util.*;
import java.util.stream.Stream;
class GFG {
// Driver code
public static void main(String[] args) {
// using Stream.generate() method
// to generate 8 random Double values
Stream.generate(new Random()::nextDouble)
.limit(8).forEach(System.out::println);
}
}
輸出:
0.5390254520295368 0.8477297185718798 0.23703352435894398 0.09156832989674057 0.9671295321757734 0.9989670394813547 0.8909416330715489 0.08177639888829968
相關用法
- Java Stream.max()用法及代碼示例
- Java Stream min()用法及代碼示例
- Java Stream count()用法及代碼示例
- Java Stream dropWhile()用法及代碼示例
- Java Stream skip()用法及代碼示例
- Java Stream takeWhile()用法及代碼示例
- Java Stream ofNullable(T)用法及代碼示例
- Java Stream forEachOrdered()用法及代碼示例
- Java Stream noneMatch()用法及代碼示例
- Java Optional stream()用法及代碼示例
- Java BitSet stream()用法及代碼示例
- Java Stream forEach()用法及代碼示例
- Java OptionalLong stream()用法及代碼示例
注:本文由純淨天空篩選整理自Sahil_Bansall大神的英文原創作品 Stream generate() method in Java with examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。