如何在Java对字符串数组进行排序
字符串数组
要在Java对字符串数组进行排序,我们可以使用 Arrays.sort()函数。
// A sample Java program to
// sort an array of strings
// in ascending and descending
// orders using Arrays.sort().
import java.util.Arrays;
import java.util.Collections;
public class SortExample {
public static void main(String[] args)
{
String arr[] = { "practice.geeksforgeeks.org",
"quiz.geeksforgeeks.org",
"code.geeksforgeeks.org" };
// Sorts arr[] in ascending order
Arrays.sort(arr);
System.out.printf("Modified arr[] : \n%s\n\n",
Arrays.toString(arr));
// Sorts arr[] in descending order
Arrays.sort(arr, Collections.reverseOrder());
System.out.printf("Modified arr[] : \n%s\n\n",
Arrays.toString(arr));
}
}
输出:
Modified arr[] :
Modified arr[] :
[quiz.geeksforgeeks.org, practice.geeksforgeeks.org, code.geeksforgeeks.org]
字符串数组列表
如果我们有一个 ArrayList 要排序,我们可以使用 Collections.sort()
// A sample Java program to sort
// an arrayList of strings
// in ascending and descending
// orders using Coolections.sort().
import java.util.ArrayList;
import java.util.Collections;
public class SortExample {
public static void main(String[] args)
{
ArrayList al = new ArrayList();
al.add("practice.geeksforgeeks.org");
al.add("quiz.geeksforgeeks.org");
al.add("code.geeksforgeeks.org");
// Sorts ArrayList in ascending order
Collections.sort(al);
System.out.println(
"Modified ArrayList : \n" + al);
// Sorts arr[] in descending order
Collections.sort(al,
Collections.reverseOrder());
System.out.println(
"Modified ArrayList : \n" + al);
}
}
输出:
Modified ArrayList :
Modified ArrayList :
[quiz.geeksforgeeks.org, practice.geeksforgeeks.org, code.geeksforgeeks.org]