更新时间:2023-11-29 16:22:46
从 Collections.sort,采用自定义比较器.您需要编写一个自定义的 Comparator为此也.
Start with Collections.sort, the one that takes a custom Comparator. You'll need to write a custom Comparator for this also.
例如,假设您想依赖于它们的 compareTo 方法中定义的字符串的自然顺序:
For instance, assuming you want to rely on the natural ordering of Strings as defined in their compareTo method:
public static void main(String[] args) throws Exception {
ArrayList<String[]> listOfStringArrays = new ArrayList<String[]>();
listOfStringArrays.add(new String[] {"x","y","z"});
listOfStringArrays.add(new String[] {"a","b","c"});
listOfStringArrays.add(new String[] {"m","n","o"});
Collections.sort(listOfStringArrays,new Comparator<String[]>() {
public int compare(String[] strings, String[] otherStrings) {
return strings[1].compareTo(otherStrings[1]);
}
});
for (String[] sa : listOfStringArrays) {
System.out.println(Arrays.toString(sa));
}
/* prints out
[a, b, c]
[m, n, o]
[x, y, z]
*/
}