如何在Java中按升序对 ArrayList 进行排序
给定一个未排序的 ArrayList,任务是在Java中按升序对该 ArrayList 进行排序。
例子:
Input: Unsorted ArrayList: [Geeks, For, ForGeeks, GeeksForGeeks, A computer portal]
Output: Sorted ArrayList: [A computer portal, For, ForGeeks, Geeks, GeeksForGeeks]
Input: Unsorted ArrayList: [Geeks, For, ForGeeks]
Output: Sorted ArrayList: [For, ForGeeks, Geeks]
方法:可以使用Java中 Collections 类的 sort() 方法对 ArrayList 进行排序。这个 sort() 方法将要排序的集合作为参数,默认返回一个按升序排序的集合。
句法:
Collections.sort(ArrayList);
下面是上述方法的实现:
// Java program to demonstrate
// How to sort ArrayList in ascending order
import java.util.*;
public class GFG {
public static void main(String args[])
{
// Get the ArrayList
ArrayList
list = new ArrayList();
// Populate the ArrayList
list.add("Geeks");
list.add("For");
list.add("ForGeeks");
list.add("GeeksForGeeks");
list.add("A computer portal");
// Print the unsorted ArrayList
System.out.println("Unsorted ArrayList: "
+ list);
// Sorting ArrayList in ascending Order
// using Collection.sort() method
Collections.sort(list);
// Print the sorted ArrayList
System.out.println("Sorted ArrayList "
+ "in Ascending order : "
+ list);
}
}
输出:
Unsorted ArrayList: [Geeks, For, ForGeeks, GeeksForGeeks, A computer portal]
Sorted ArrayList in Ascending order : [A computer portal, For, ForGeeks, Geeks, GeeksForGeeks]