这里可能最简单(但不是最漂亮)的方法是将值简单地拆分为前缀(实际值)和后缀(测量值),然后分别进行比较。
所以我实现了一个Comparator<String>,它将给定的值分成前缀和后缀,然后首先按字母顺序比较后缀。 (免责声明:大写字母将被视为比小写字母“更小”)如果它们相等,则比较前缀值。
下面是一个描述逻辑的小例子:
import java.util.Arrays;
import java.util.Comparator;
public class Test {
public static void main(String[] args) {
String input = "50ml,100g,3.5ml,10g,0.4g,320ml,32.3a,3.6ml";
String[] splitInput = input.split(",");
System.out.println("Before:\t" + Arrays.toString(splitInput));
Arrays.sort(splitInput, new MyComparator());
System.out.println("After:\t" + Arrays.toString(splitInput));
}
static class MyComparator implements Comparator<String> {
@Override
public int compare(String o1, String o2) {
// extract the suffix by removing the digits and dots
String suffix1 = o1.replaceAll("[\\d\\.]", "");
String suffix2 = o2.replaceAll("[\\d\\.]", "");
if (suffix1.compareTo(suffix2) != 0) {
return suffix1.compareTo(suffix2); // String#compareTo
}
// extract the prefix by removing the characters
double value1 = Double.parseDouble(o1.replaceAll("[A-Za-z]", ""));
double value2 = Double.parseDouble(o2.replaceAll("[A-Za-z]", ""));
// compare the double values
return (int) Double.compare(value1, value2);
}
}
}
输出:
Before: [50ml, 100g, 3.5ml, 10g, 0.4g, 320ml, 32.3a, 3.6ml]
After: [32.3a, 0.4g, 10g, 100g, 3.5ml, 3.6ml, 50ml, 320ml]