📌  相关文章
📜  如何在Java对字符串数组进行排序

📅  最后修改于: 2022-05-13 01:55:25.248000             🧑  作者: Mango

如何在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));
    }
}
输出:

字符串数组列表

如果我们有一个 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);
    }
}
输出: