Search code examples
javastringrandomintegerjava-stream

How to generate random String of numbers?


I need to generate a String of random ints, and I could use a loop

import java.util.Random;

public class RandomNumbers {
    public static void main(String[] args) {
        Random r = new Random();
        String pageReferenceString = "";
        for (int i = 0; i < 100; i++) {
            pageReferenceString += String.valueOf(r.nextInt(9));
        }
        System.out.println(pageReferenceString);
    }
}

But, it seems too complicated, I could also have used streams

import java.util.Random;
import java.util.stream.IntStream;

public class StreamRandomNumbers {
    public static void main(String[] args) {
        Random r = new Random();
        String pageReferenceString = IntStream
            .generate(() -> r.nextInt(9))
            .limit(100)
            .mapToObj(String::valueOf)
            .reduce((a, b) -> a+b) // a.concat(b)
            .get();
        System.out.println(pageReferenceString);
    }
}

But it is still too complicated.

Is there a simple way of doing this?


Solution

  • Try using java.math.BigInteger to represent a 100-decimal digit number to string:

    String s = new java.math.BigInteger(336,new Random()).toString().substring(0,100);
    System.out.println(s.length() + " : " + s);
    

    Produces:

    100 : 3627584459248992174732353013411646520422611738128940010551544228607987109715317481157384457047726562
    

    336 is the number of bits required to ensure a 100-digit number and account for a "missing" leading 0.