您需要使用Arrays.sort()为此自定义Comparator:
Arrays.sort(array, new CustomComparator());
public class CustomComparator implements Comparator {
private final Pattern pattern = Pattern.compile("(\d+)\s+(.*)");
public int compare(String s1, String s2) {
Matcher m1 = pattern.matcher(s1);
if (!m1.matches()) {
throw new IllegalArgumentException("s1 doesn't match: " + s1);
}
Matcher m2 = pattern.matcher(s2);
if (!m2.matches()) {
throw new IllegalArgumentException("s2 doesn't match: " + s2);
}
int i1 = Integer.parseInt(m1.group(1));
int i2 = Integer.parseInt(m2.group(1));
if (i1 < i2) {
return 1;
} else if (i1 > i2) {
return -1;
}
return m1.group(2).compareTo(m2.group(2));
}
}
上面的假设您的数组元素是类似“ 22 ASomething”的字符串,而不是包含出现次数和某些文本的特定数据结构.在这种情况下,您可以使用更简单的比较器.
同样,如果您确实有一个Strings数组,可能值得首先将其转换为一个已解析的对象数组,以节省对元素的过度解析(即,某些元素将被解析多次).