Java: Randomly generate distinct names

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

    // class variable
    final String lexicon = "ABCDEFGHIJKLMNOPQRSTUVWXYZ12345674890";
    
    final java.util.Random rand = new java.util.Random();
    
    // consider using a Map to say whether the identifier is being used or not 
    final Set identifiers = new HashSet();
    
    public String randomIdentifier() {
        StringBuilder builder = new StringBuilder();
        while(builder.toString().length() == 0) {
            int length = rand.nextInt(5)+5;
            for(int i = 0; i < length; i++) {
                builder.append(lexicon.charAt(rand.nextInt(lexicon.length())));
            }
            if(identifiers.contains(builder.toString())) {
                builder = new StringBuilder();
            }
        }
        return builder.toString();
    }
    

提交回复
热议问题