Tuesday, August 20, 2013

How to generate Alphanumeric with Apache commons-id

Instead of numeric sequence number, alphanumeric sequence may more occurrences.
Because a single number has only 10 occurrences (0-9), but a single alphanumeric sequence has 36 occurrences (0-9 + a-z).

It is a tedious work if we write our own codes to generate the alphanumeric sequence.
There is an easy way with Apache commons id.

Apache commons id is not release yet, but we can download it here.
Although using a pre-release library is not a good practice, but use only 1 class/function should be not a big issue.



Steps to use the AlphanumericGenerator:

1. Initiate the AlphanumericGenerator constructor.
    There are 3 constructors for us to choose, details please refer the api.
AlphanumericGenerator generator = new AlphanumericGenerator(false);

// length of the alphanumeric text is 5
AlphanumericGenerator generator = new AlphanumericGenerator(false, 5);

// start from 0s, the next text to generate is 0t
AlphanumericGenerator generator = new AlphanumericGenerator(false, "0s");

2. Generate next alphnumeric text.
String anText = generator.nextStringIdentifier();


Done!!

No comments:

Post a Comment

LinkWithin

Related Posts Plugin for WordPress, Blogger...