Split Random Streams With SplittableRandom
Generate reproducible random sequences with SplittableRandom and split independent child generators for parallel tasks.
Code
import java.util.SplittableRandom;
import java.util.stream.IntStream;
public class SplittableRandomDemo {
public static void main(String[] args) {
// 固定种子:同一 JDK 上序列可复现
SplittableRandom random = new SplittableRandom(42);
System.out.println("first three: "
+ random.nextInt(100) + " "
+ random.nextInt(100) + " "
+ random.nextInt(100));
// split 产生共享同一算法的独立子生成器
SplittableRandom left = random.split();
SplittableRandom right = random.split();
System.out.println("left: " + left.nextInt(1_000));
System.out.println("right: " + right.nextInt(1_000));
// splits 返回由子生成器产生的有界随机值流
long distinctValues = random.splits(8, 0, 1_000)
.distinct()
.count();
System.out.println("distinct split values: " + distinctValues);
// IntStream 与 SplittableRandom 组合生成有界数据集
int total = IntStream.generate(() -> random.nextInt(1, 7))
.limit(100)
.sum();
System.out.println("dice total: " + total);
System.out.println("range check: " + random.nextInt(5, 10));
}
}What the code does
The working surface is the class SplittableRandomDemo and the function main — everything else is wiring.
Applying it
Each run prints the 6 labeled blocks first three:, left:, right:, distinct split values:, dice total:, range check: in source order.
Statements that matter
int total = IntStream.generate(() -> random.nextInt(1, 7))
.limit(100)
.sum();
SplittableRandom random = new SplittableRandom(42);
long distinctValues = random.splits(8, 0, 1_000)
.distinct()
.count();
Interactive Tools for This Topic
Passphrase GeneratorGenerate memorable multi-word passphrases from a fixed 150-word list with crypto randomness, separators, and capitalization options.Password GeneratorGenerate random passwords from selectable character classes using crypto.getRandomValues with rejection sampling and class guarantees.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.UUID v4 GeneratorGenerate cryptographically random UUIDs version 4 using the Web Crypto API. Produce single or batch UUIDs with optional uppercase formatting and copy-to-clipboard support.
FAQ
- What does Split Random Streams With SplittableRandom print when run?
- Invoke the file as-is — the `first three:`, `left:`, `right:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.