JAVA通过数组按首字母排序

例John Bill Peter 按升序输出Bill John Peter倒序如何改?
2024-12-02 07:03:49
推荐回答(3个)
回答1:

package demo;

import java.util.Arrays;

public class Test {

public void sortStringArray() {
String[] arrayToSort = new String[] { "Oscar", "Charlie", "Ryan",
"Adam", "David","aff","Aff" };
System.out.println();
System.out.println("字符型数组排序,排序前:");
for (int i = 0; i < arrayToSort.length; i++){
System.out.print(arrayToSort[i]+",");
}
System.out.println();
System.out.println("排序后:");
// 调用数组的静态排序方法sort,且不区分大小写
Arrays.sort(arrayToSort,String.CASE_INSENSITIVE_ORDER);

for (int i = 0; i < arrayToSort.length; i++){
System.out.print(arrayToSort[i]+",");
}
}

public static void main(String[] args) {
new Test().sortStringArray();

}

}
运行结果:
字符型数组排序,排序前:
Oscar,Charlie,Ryan,Adam,David,aff,Aff,
排序后:
Adam,aff,Aff,Charlie,David,Oscar,Ryan,
希望对你有帮助

回答2:

static void sort(Object[] a)
这个方法按照字母顺序排序,如果不满意的话你还可以自己写比较器。
static void sort(T[] a, Comparator c) ;

回答3:

public static void main(String[] args) {
String[] s = {"John","Bill","Peter","Abc"};
reverseArray(s);
}
public static void reverseArray(String[] arr){
Arrays.sort(arr);
List list = Arrays.asList(arr);
Collections.reverse(list);
System.out.println( list );
}