Charlotte Charlotte - 1 year ago 118
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 Source
// 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++) {
        if(identifiers.contains(builder.toString())) {
            builder = new StringBuilder();
    return builder.toString();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download