1 回答

TA贡献1797条经验 获得超6个赞
这是由于 ASCII 字符集的顺序,其中 'Z' 先于 'a'
RuleBasedCollator 仅检查要排序的字符串的第一个字母。正如您设定的规则是(A < a)。它首先列出所有以大写字母开头的字符串,然后是小写字母。
由于您的列表包含以特殊字符开头的字符串,我建议创建两个列表进行排序。一个用于以特殊字符开头的字符串,然后是包含所有其他值的其他列表。分别对这两个列表进行排序,然后合并排序后的列表。我已经尝试了下面的代码,它工作正常
// Input list
List<String> name = new ArrayList<String>();
final String[] specialChars = { "_", ">" };
List<String> specCharList = new ArrayList<String>();
List<String> strList = new ArrayList<String>();
List<String> finalList = new ArrayList<String>();
String rules = "< '_' < '>' ";
boolean isSpec = false ;
for(String names : name) {
isSpec = false ;
for(int i=0;i<specialChars.length;i++) {
if(names.startsWith(specialChars[i])) {
// System.out.println("Name : "+names);
isSpec = true ;
}
}
// to sort special char list and normal list
if(isSpec) {
specCharList.add(names);
} else {
strList.add(names);
}
}
try {
// To sort special character list
Collections.sort(specCharList, new RuleBasedCollator(rules));
// Add the sorted list to finallist
finalList.addAll(specCharList);
// to sort other list
Collections.sort(strList, String.CASE_INSENSITIVE_ORDER);
// Add the sorted list to finallist
finalList.addAll(strList);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Final Output List --------");
for(String names : finalList) {
System.out.println(names);
}
添加回答
举报