我的输入字符串数组如下:
String [] arr = {“ 2T1BURHE1JCO24154C”, “ 2TABURHE1JC024154C”, “ JTDKARFP5H3055472C”, “ 2T2BURHE1JCO24154C”, “ JTDKARFP1H3056246C”};
输出数组应如下所示:
{"JTDKARFP1H3056246C",
"JTDKARFP5H3055472C",
"2TABURHE1JC024154C",
"2T1BURHE1JCO24154C",
"2T2BURHE1JCO24154C"}
在以下模式中给出了优先级:
[ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789]
当我在Java中使用Arrays.sort(arr)时,它将以字典模式对数组进行排序,并提供以下输出:
[2T1BURHE1JCO24154C,2T2BURHE1JCO24154C,2TABURHE1JC024154C,JTDKARFP1H3056246C,JTDKARFP5H3055472C]
如何用Java实现这一目标。
谢谢。
答案 0 :(得分:4)
您需要自定义比较器,可以通过比较角色在order
中的位置来实现:
public static void main(String[] args) {
String[] arr = {"2T1BURHE1JCO24154C",
"2TABURHE1JC024154C",
"JTDKARFP5H3055472C",
"2T2BURHE1JCO24154C",
"JTDKARFP1H3056246C"};
String order = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Arrays.sort(arr, (first, second) -> {
for (int index = 0; index < second.length(); index++) {
int charFirst = (int) (first.charAt(index));
int charSecond = (int) (second.charAt(index));
if (order.indexOf(charFirst) > order.indexOf(charSecond)) {
return 1;
} else if (order.indexOf(charFirst) < order.indexOf(charSecond)) {
return -1;
} else {
continue;
}
}
return 0;
});
for (String s : arr) {
System.out.println(s);
}
}
输出:
JTDKARFP1H3056246C
JTDKARFP5H3055472C
2TABURHE1JC024154C
2T1BURHE1JCO24154C
2T2BURHE1JCO24154C
答案 1 :(得分:2)
看起来像约翰斯的作品,我认为这有点干净。
String order = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Comparator<String> c = (s1, s2) -> {
int minLen = Math.min(s1.length(), s2.length());
for (int i = 0; i < minLen; i++) {
char s1Char = s1.charAt(i);
char s2Char = s2.charAt(i);
if (s1Char == s2Char) {
//if characters are the same skip
continue;
} else {
//if the characters are diff get precedence
return order.indexOf(s1Char) - order.indexOf(s2Char);
}
}
// if all chars are the same the longer one is last
return s1.length() - s2.length();
};