1

I need to create alphanumeric unique IDs of length 7 or 10. Similar to the shorter version of Git commit IDs (7a471b2).

I tried UUID, but the generated unique ID is longer than I need.

Is there a built-in method / code snippet in Java that can help here?

user2864740
  • 60,010
  • 15
  • 145
  • 220
Veera
  • 32,532
  • 36
  • 98
  • 137

4 Answers4

1

If you want to generate random values you should use SecureRandom

  SecureRandom random = new SecureRandom();
  byte bytes[] = new byte[15];
  random.nextBytes(bytes);

To get the proper key length you may want to convert that into your expected from. The characters are also number, so you can generate longer random value and afterward just encode it. You may want to use Base64 or hext for that. In Java you use DatatypeConverter

String key = DatatypeConverter.printBase64Binary(random);

our use Apache

org.apache.commons.codec.binary.Base64

String key = new String(Base64.encodeBase64(random));

There is not Java class that support generation of random values in that form.

1

You did not mention whether you need the number to be generated in a state-less manner. You only need this if you have many sources generating IDs whereas each source is independent and does not know of any state of any other sources. For such a case UUID allows to generate ID's that yre still very unlikely to collide.

If you are the only source generating ID's, then you can make use of state. As an example, in a database you often simply use a sequence to generate IDs (the state being the nextval of the sequence). These numbers are perfectly unique too. If you need it to "look" random, there are algorithms to shuffle the number space by mapping each sequential number onto a random-looking number.

A second example of "state" is the set of all IDs already in use. You can use this by generating a "random" number in an arbitrarily primitive way and then matching it against all your existing numbers. If it collides, generate another one.

chiccodoro
  • 14,407
  • 19
  • 87
  • 130
0

Try Apache lang RandomStringUtils class

Koti
  • 131
  • 4
0

This is not as simple as it looks like. First of all UUID is not 100% unique. It can only produce 2^128 unique numbers (I might be wrong about the 128 number. But you get the idea).

Making it shorter will only increase the probability of repetition.

The best way I could think of right now is to take the UUID and use some base64 encoder over it.

[EDIT] Alternatively, use Random.nextInt and increment by one each time you need a new ID.

Hirak
  • 3,601
  • 1
  • 22
  • 33