Split Random Streams With SplittableRandom

Generate reproducible random sequences with SplittableRandom and split independent child generators for parallel tasks.

JavaData Integrity

Code

snippet
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

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.