I have a List of Strings. EXAMPLE_1, EXAMPLE_2, EXAMPLE_3 … EXAMPLE_99
What is the best algorithm for sorting here?
Is it possible with a Collator?
This is my current procedure, but I guess there could be a better way:
public class Example implements Comparable<Example> {
private final String id;
public getId() {
return id;
}
private Integer getIdNo() {
try {
return Integer.parseInt(getId().replaceAll("[\\D]", ""));
} catch (NumberFormatException e) {
return null;
}
}
@Override
public int compareTo(Example o) {
if ((getIdNo() == null && getIdNo() != null) || (getProductFeatureId_sizeNo() < o.getProductFeatureId_sizeNo())) {
return -1;
} else if (o.getIdNo() == null || getIdNo() > o.getIdNo()) {
return 1;
}
return 0;
}
}
This is better alternative – AlphanumComparator.java
Copying the code for ready reference –
Note: you should generify this class if you’re using java 1.5+