我有以下形式的字符串数组列表:
{T1,C1,C2,T2,C3,T3,A1,T4,G1,A2,G2,A3,T5,C4,C5,T6,A4,T7,T8,C6,T9,A5,T10, G3,A6,A7,A8,C7,C8,T11,T12,C9,A9,$ 1,G4,A10,C10,C11,A11,A12,A13,A14,T13,T14,C12,T15,C13,C14, G5,G6,C15}
我想将此数组列表排序为以下内容:
{$ 1,A1,A2 ... A10,A11,... C1,C2 ... C14 ....}。
但是,当我使用Collections.sort()
时,结果却是:
带A2的{$ 1,A1,A10,A11,A12,A13,A14,A2,A3,A4,A5,A6,A7,A8,A9,C1,C10,C11,C12,C13,C14,C15,C2, C3,C4,C5,C6,C7,C8,C9,G1,G2,G3,G4,G5,G6,T1,T10,T11,T12,T13,T14,T15,T2,T3,T4,T5,T6, T7,T8,T9}
在A14之后。那么有没有办法解决这个问题呢?非常感谢!
答案 0 :(得分:4)
您可以使用Comparator.comparing()
方法链来定义排序标准。在第一个字符上将第一个比较定义为Character
排序,然后在其余子字符串上将第二个比较定义为Integer
排序:
String[] arr = {"T1", "C1", "C2", "T2", "C3", "T3", "A1", "T4", "G1", "A2", "G2", "A3", "T5",
"C4", "C5", "T6", "A4", "T7", "T8", "C6", "T9", "A5", "T10", "G3", "A6", "A7", "A8", "C7",
"C8", "T11", "T12", "C9", "A9", "$1", "G4", "A10", "C10", "C11", "A11", "A12", "A13",
"A14", "T13", "T14", "C12", "T15", "C13", "C14", "G5", "G6", "C15"};
Arrays.sort(arr, Comparator.<String, Character>comparing(s -> s.charAt(0))
.thenComparingInt(s -> Integer.parseInt(s.substring(1))));
System.out.println(Arrays.toString(arr));
将打印
[$1, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12, C13, C14, C15, G1, G2, G3, G4, G5, G6, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15]
答案 1 :(得分:0)
您必须创建自己的Comparator
对象,才能以默认顺序以外的其他顺序进行排序。当您不提供自己的比较器时,字符串按字典顺序排序。可以使用Collection.sort
的新方法来代替List
。
myList.sort(new MyComparator());
类MyComparator
是Comparator
的实例:
class MyComparator implements Comparator<String> {
...
}
您必须实现方法compareTo
。