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
Asked
Active
Viewed 2,068 times
-5
-
am not getting any idea so i posted – Deep Chand Jaipur Jul 12 '16 at 08:48
-
2please go through http://stackoverflow.com/help/how-to-ask – Abhishek Jul 12 '16 at 08:49
1 Answers
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
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