[英]Sort a String array in java (special way)
I have a problem doing this since I need to sort it in this way: 我有一个问题,因为我需要以这种方式进行排序:
Before: 之前:
{aAbB, abBA, AaBb}
After: 后:
{AaBb, aAbB, abBA}
The idea is sorting a uppercase letter right before it's lowercase version, and that with every letter. 这个想法是在大写字母排序之前,先将其转换为小写字母,然后再对每个字母进行排序。 I'm actually using a Collator for Spanish (problems with the 'ñ') and set it's strength to PRIMARY so I can compare if two words are equal not having care of capital letters.
我实际上是在使用西班牙语的整理程序(“ñ”问题)并将其强度设置为PRIMARY,这样我就可以比较两个单词是否相等而不必大写。
Just do: 做就是了:
private static Comparator<String> ALPHABETICAL_ORDER = new Comparator<String>() {
public int compare(String str1, String str2) {
int res = String.CASE_INSENSITIVE_ORDER.compare(str1, str2);
if (res == 0) {
res = (str1.compareTo(str2)==0) ? 1 : 0;
}
return res;
}
};
Collections.sort(list, ALPHABETICAL_ORDER);
Inspired from: Simple way to sort strings in the (case sensitive) alphabetical order 启发自: 一种按(区分大小写)字母顺序对字符串排序的简单方法
这将产生所需的结果。
Arrays.sort(stringArray)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.