Java: Randomly generate distinct names

前端 未结 8 721
臣服心动
臣服心动 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:22

    If you permit Apache Commons lang...

    public String[] getRandomlyNames(final int characterLength, final int generateSize) {
        HashSet list = new HashSet();
        for (int i = 0; i < generateSize; ++i) {
            String name = null;
            do {
                name = org.apache.commons.lang.RandomStringUtils.randomAlphanumeric(
                        org.apache.commons.lang.math.RandomUtils.nextInt(characterLength - 1) + 1);
            while(list.contains(name));
            list.add(name);
        }
        return list.toArray(new String[]{});
    }
    

提交回复
热议问题