Sort Items in the Collection
Use Collections from java.util to sort our list.
Let’s have a look at the sample below:
import org.apache.commons.lang3.StringUtils;
import java.util.*;
public class Main {
public static void main(String[] args) {
String[] products = {"P001-1ML", "P001-0.5ML", "P001-100ML", "P001-25ML", "P001-0.7ML", "P001-20ML", "P001-1ML", "P001-0.1ML"};
List<String> listProductCode = Arrays.asList(products);
Collections.sort(listProductCode, new Comparator<String>() {
@Override
public int compare(String code1, String code2) {
float number1 = getNumber(code1);
float number2 = getNumber(code2);
if (number1 - number2 > 0) {
return 1;
} else if (number1 - number2 == 0) {
return 0;
}
return -1;
}
float getNumber(String value) {
String number = value.replaceAll("[a-zA-Z-]", StringUtils.EMPTY);
return number.isEmpty() ? 0 : Float.parseFloat(number);
}
});
listProductCode.forEach(item -> System.out.println(item));
}
}
The result:
P001-0.1ML
P001-0.5ML
P001-0.7ML
P001-1ML
P001-1ML
P001-20ML
P001-25ML
P001-100ML
Process finished with exit code 0