如何使用比较器或类似方法基于ACII表对字符串列表进行升序或降序排序。
让我们假设一个字符串列表包含以数字(1start)或特殊字符(@fill)或小写(kind)或大写(Link)开头的单词
示例场景: 我想按以下特定顺序对列表进行排序:(对asc或desc进行排序)
答案 0 :(得分:1)
我将为这些“字符类”中的每一个创建一个枚举,并用某种逻辑找出每个字符所属的类:
public enum CharacterClass {
LOWERCASE, SPECIAL, NUMBER, UPPERCASE;
public static CharacterClass getClass(char c) {
if (Character.isLowerCase(c)) {
return LOWERCASE;
}
if (Character.isUpperCase(c)) {
return UPPERCASE;
}
if (Character.isDigit(c)) {
return NUMBER;
}
return SPECIAL;
}
}
基于此,我们现在可以创建一个比较器,该比较器遍历两个字符串的字符并比较它们的类(如果它们具有相同的类,则比较字符本身):
public class CharacterClassComparator implements Comparator<String> {
@Override
public int compare(String o1, String o2) {
int l1 = o1.length();
int l2 = o2.length();
int length = Math.min(l1, l2);
for (int i = 0; i < length; ++i) {
char c1 = o1.charAt(i);
char c2 = o2.charAt(i);
// Compare the character classes
int res = CharacterClass.getClass(c1).compareTo(CharacterClass.getClass(c2));
if (res != 0) {
return res;
}
// If the clases are the same, compare the actual characters
res = Character.compare(c1, c2);
if (res != 0) {
return res;
}
}
// All the characters up to the shared length are the same
// Compare the lengths:
return Integer.compare(l1, l2);
}
}