Charlotte Charlotte - 2 months ago 18
Java Question

Java: Randomly generate distinct names

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 libraries would be an extra plus.

Answer
// class variable
final String lexicon = "ABCDEFGHIJKLMNOPQRSTUVWXYZ12345674890";

final java.util.Random rand = new java.util.Random();

// consider using a Map<String,Boolean> to say whether the identifier is being used or not 
final Set<String> identifiers = new HashSet<String>();

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();
}
Comments