-5

How to generate ordered sequential unique id in a java program. The output should be: here is the sample output Mys2016vj01 in the output the 01 should be increment till the year. after the year 2016 should be increments to 2017 so on then when year changes after the constant vj number should be reset to 01

1 Answers1

0
//Initialize it as a static field in the class where you want to generate random number.
private static final UniqueParamBuilder UNIQUE_PARAM_BUILDER = new UniqueParamBuilder();

public String buildNextUniqueNumber() {
     //Params can be final depending on your context.
     String param1 = "Mys";
     String param2 = "vj";

     int year = LocalDateTime.now().getYear();//Java 8. If Java 7, check this

I want to get Year, Month, Day, etc from Java Date to compare with Gregorian Calendar date in Java. Is this possible?

     String yearParam = year + "";
     int uniqueNumber = UNIQUE_PARAM_BUILDER.getNext(year);
     String uniqueParam = String.format("%01d", uniqueNumber); //Check this to see how start string with leading zeros.

How can I pad an integers with zeros on the left?

     String result = param1 + yearParam + param2 + uniqueParam;
     return result;
}

public class UniqueParamBuilder {

    private static final YEAR_TO_START = 2015;
    private static final int START_CONTER = 0;

    private int previousYear = YEAR_TO_START;
    private int counter = START_CONTER ;

    public int getNext(int year) {
        if (year > previousYear) {
             previousYear = year;
             resetCounter();
        }
        counter++;//Start counter with 1.
        return counter;
    }

    private void resetCounter() {
         counter = START_CONTER ;
    }
}
Community
  • 1
  • 1
Yan Khonski
  • 12,225
  • 15
  • 76
  • 114