Java: Randomly generate distinct names

前端 未结 8 748
臣服心动
臣服心动 2020-12-09 04:58

I need to generate 10,000 unique identifiers in Java. The identifiers should be a mixture of numbers and letters and less than 10 characters each. Any ideas? Built in librar

8条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-09 05:27

    I had the same problem, but I needed an arbitrarily long string. I came up with this one-liner, no external library needed, that will give you 10 characters:

    BigInteger.probablePrime(50, new Random()).toString(Character.MAX_RADIX)
    

    The length can be changed, you need about 5 bits per character. What did is filter and limit the length as follows (just lowercase letters, and size 10):

    BigInteger.probablePrime(100, new Random()).
        toString(Character.MAX_RADIX).
        replaceAll("[0-9]", "").
        substring(0, 10) 
    

    Disadvantage: it's a bit slow.

提交回复
热议问题