Search code examples
javastringalphanumeric

How to auto increment an alpha numeric id in Java


I want to implement a functionality that auto increment an alpha numeric id in a Java program.

The ids types are Strings, have only digits and lower case latin letters, and is case insensitive.

Basically, I want a function called static String next(String id) that gives what should be the next id.

The id should increase from right to left, and new characters should be added on the left.

For example

assertEquals("1", IdUtils.next("0"));
assertEquals("a", IdUtils.next("9"));
assertEquals("10", IdUtils.next("z"));
assertEquals("10", IdUtils.next("0z"));
assertEquals("100", IdUtils.next("zz"));
assertEquals("zz1", IdUtils.next("zz0"));
assertEquals("zza", IdUtils.next("zz9"));

Thanks in advance.


Solution

  • A number with digits and lower case latin letters is a base-36 number, which is an extension of base-16, also known as hex.

    So to increment the base-36 number, parse it, increment it, and convert back to text.

    static String next(String id) {
        return Long.toString(Math.incrementExact(Long.parseLong(id, 36)), 36);
    }
    

    Test

    System.out.println(next("0"));
    System.out.println(next("9"));
    System.out.println(next("z"));
    System.out.println(next("zzzzzz"));
    System.out.println(next("dif5613ug"));
    System.out.println(next("1y2p0ij32e8e6"));
    System.out.println(next("1y2p0ij32e8e7")); // Long.MAX_VALUE, so will overflow
    

    Output

    1
    a
    10
    1000000
    dif5613uh
    1y2p0ij32e8e7
    Exception in thread "main" java.lang.ArithmeticException: long overflow