How do I create a unique ID in Java?

JavaUniqueidentifier

Java Problem Overview


I'm looking for the best way to create a unique ID as a String in Java.

Any guidance appreciated, thanks.

I should mention I'm using Java 5.

Java Solutions


Solution 1 - Java

Create a UUID.

String uniqueID = UUID.randomUUID().toString();

Solution 2 - Java

If you want short, human-readable IDs and only need them to be unique per JVM run:

private static long idCounter = 0;

public static synchronized String createID()
{
    return String.valueOf(idCounter++);
}    

Edit: Alternative suggested in the comments - this relies on under-the-hood "magic" for thread safety, but is more scalable and just as safe:

private static AtomicLong idCounter = new AtomicLong();

public static String createID()
{
    return String.valueOf(idCounter.getAndIncrement());
}

Solution 3 - Java

java.util.UUID : toString() method

Solution 4 - Java

Here's my two cent's worth: I've previously implemented an IdFactory class that created IDs in the format [host name]-[application start time]-[current time]-[discriminator]. This largely guaranteed that IDs were unique across JVM instances whilst keeping the IDs readable (albeit quite long). Here's the code in case it's of any use:

public class IdFactoryImpl implements IdFactory {
  private final String hostName;
  private final long creationTimeMillis;
  private long lastTimeMillis;
  private long discriminator;

  public IdFactoryImpl() throws UnknownHostException {
    this.hostName = InetAddress.getLocalHost().getHostAddress();
    this.creationTimeMillis = System.currentTimeMillis();
    this.lastTimeMillis = creationTimeMillis;
  }

  public synchronized Serializable createId() {
    String id;
    long now = System.currentTimeMillis();

    if (now == lastTimeMillis) {
      ++discriminator;
    } else {
      discriminator = 0;
    }

    // creationTimeMillis used to prevent multiple instances of the JVM
    // running on the same host returning clashing IDs.
    // The only way a clash could occur is if the applications started at
    // exactly the same time.
    id = String.format("%s-%d-%d-%d", hostName, creationTimeMillis, now, discriminator);
    lastTimeMillis = now;

    return id;
  }

  public static void main(String[] args) throws UnknownHostException {
    IdFactory fact = new IdFactoryImpl();
    
    for (int i=0; i<1000; ++i) {
      System.err.println(fact.createId());
    }
  }
}

Solution 5 - Java

Generate Unique ID Using Java

UUID is the fastest and easiest way to generate unique ID in Java.

import java.util.UUID;

public class UniqueIDTest {
  public static void main(String[] args) {
    UUID uniqueKey = UUID.randomUUID();
    System.out.println (uniqueKey);
  }
}

Solution 6 - Java

IMHO aperkins provided an an elegant solution cause is native and use less code. But if you need a shorter ID you can use this approach to reduce the generated String length:

// usage: GenerateShortUUID.next();
import java.util.UUID;

public class GenerateShortUUID() {

  private GenerateShortUUID() { } // singleton

  public static String next() {
     UUID u = UUID.randomUUID();
     return toIDString(u.getMostSignificantBits()) + toIDString(u.getLeastSignificantBits());
  }

  private static String toIDString(long i) {
      char[] buf = new char[32];
      int z = 64; // 1 << 6;
      int cp = 32;
      long b = z - 1;
      do {
          buf[--cp] = DIGITS66[(int)(i & b)];
          i >>>= 6;
      } while (i != 0);
      return new String(buf, cp, (32-cp));
  }

 // array de 64+2 digitos 
 private final static char[] DIGITS66 = {
	'0','1','2','3','4','5','6','7','8','9',    	'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
	'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
	'-','.','_','~'
  };

}

Solution 7 - Java

This adds a bit more randomness to the UUID generation but ensures each generated id is the same length

import org.apache.commons.codec.digest.DigestUtils;
import java.util.UUID;

public String createSalt() {
    String ts = String.valueOf(System.currentTimeMillis());
    String rand = UUID.randomUUID().toString();
    return DigestUtils.sha1Hex(ts + rand);
}

Solution 8 - Java

We can create a unique ID in java by using the UUID and call the method like randomUUID() on UUID.

String uniqueID = UUID.randomUUID().toString();

This will generate the random uniqueID whose return type will be String.

Solution 9 - Java

There are three way to generate unique id in java.

  1. the UUID class provides a simple means for generating unique ids.

    UUID id = UUID.randomUUID(); System.out.println(id);

  2. SecureRandom and MessageDigest

    //initialization of the application SecureRandom prng = SecureRandom.getInstance("SHA1PRNG");

    //generate a random number String randomNum = new Integer(prng.nextInt()).toString();

    //get its digest MessageDigest sha = MessageDigest.getInstance("SHA-1"); byte[] result = sha.digest(randomNum.getBytes());

    System.out.println("Random number: " + randomNum); System.out.println("Message digest: " + new String(result));

  3. using a java.rmi.server.UID

    UID userId = new UID(); System.out.println("userId: " + userId);

Solution 10 - Java

Unique ID with count information

import java.util.concurrent.atomic.AtomicLong;
    
public class RandomIdUtils {

    private static AtomicLong atomicCounter = new AtomicLong();
    
    public static String createId() {
    
        String currentCounter = String.valueOf(atomicCounter.getAndIncrement());
        String uniqueId = UUID.randomUUID().toString();
    
        return uniqueId + "-" + currentCounter;
    }
}

Solution 11 - Java

String name,password;

public int idGen() {

	int id = this.name.hashCode() + this.password.hashCode();
	int length = String.valueOf(id).length();
	int Max_Length = 5;
	if(String.valueOf(id).length()>Max_Length) 
	{
		id = (int) (id /Math.pow(10.0,length - Max_Length ));
	}
	return  id;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSupertuxView Question on Stackoverflow
Solution 1 - JavaaperkinsView Answer on Stackoverflow
Solution 2 - JavaMichael BorgwardtView Answer on Stackoverflow
Solution 3 - JavaMitch WheatView Answer on Stackoverflow
Solution 4 - JavaAdamskiView Answer on Stackoverflow
Solution 5 - JavaUdayKiran PulipatiView Answer on Stackoverflow
Solution 6 - JavarharariView Answer on Stackoverflow
Solution 7 - JavaRobert AldersonView Answer on Stackoverflow
Solution 8 - JavaPrabhatView Answer on Stackoverflow
Solution 9 - JavaMd Ayub Ali SarkerView Answer on Stackoverflow
Solution 10 - JavasimhumilecoView Answer on Stackoverflow
Solution 11 - JavaHatimView Answer on Stackoverflow